[小练习] 初识Swing

package com.shiyan.course;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JTextField;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class MySwingWindow extends JFrame {
    private JLabel myLabel;
    private JTextField myTextField;
    private JButton myButton;
    
    public MySwingWindow() {
        // 子类的构造函数中默认调用父类的无参构造函数
        this.setSize(400, 300);
        this.getContentPane().setLayout(null);
        this.setTitle("My First Swing Window");
        this.add(getJLabel(), null);
        this.add(getJTextField(), null);
        this.add(getJButton(), null);
    }
    
    private JLabel getJLabel() {
        if (this.myLabel == null) {
            this.myLabel = new JLabel();
            this.myLabel.setBounds(5, 10, 250, 30);
            this.myLabel.setText("Hello! Welcome to shiyanlou.com");
        }
        return this.myLabel;
    }
    
    private JButton getJButton() {
        if (this.myButton == null) {
            this.myButton = new JButton();
            this.myButton.setBounds(5, 80, 100, 40);
            this.myButton.setText("Click me!");
            this.myButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    myLabel.setForeground(Color.RED);
                    myTextField.setBackground(Color.gray);
                }
            });
        }
        return this.myButton;
    }
    
    private JTextField getJTextField() {
        if (this.myTextField == null) {
            this.myTextField = new JTextField();
            this.myTextField.setBounds(5, 45, 200, 30);
            this.myTextField.setText("Shi Yan Lou");
        }
        return this.myTextField;
    }

    public static void main(String[] args) {
        MySwingWindow window = new MySwingWindow();
        window.setVisible(true);
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容