[小練習] 初識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() {
        // 子類的構造函數(shù)中默認調(diào)用父類的無參構造函數(shù)
        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);
    }
}
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容