美文网首页
[小练习] 初识Swing

[小练习] 初识Swing

作者: 大写K | 来源:发表于2019-10-23 16:35 被阅读0次
    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);
        }
    }
    

    相关文章

      网友评论

          本文标题:[小练习] 初识Swing

          本文链接:https://www.haomeiwen.com/subject/zrmkvctx.html