JAVA中按鈕的事件監聽的三種方式


JAVA中的Swing組件,按鈕的重點是進行事件的監聽,可以通過調用JButton的addActionListener()方法。這個方法接受一個實現ActionListener接口的對象作為參數,ActionListener接口中只包含一個actionPerformed()方法,所以如果想把事件處理的代碼與JButton進行關聯,就需要如下的三種做法:

第一種:

public class Button extends MyFrame {
    private JButton
        b1 = new JButton("Button1"),
        b2 = new JButton("Button2");
    private JTextField txt = new JTextField(10);
    class ButtonListener implements ActionListener{// 定義內部類實現事件監聽
        public void actionPerformed(ActionEvent e) {
            txt.setText(((JButton)e.getSource()).getText()) ;
            /*
             * String name = ((JButton)e.getSource()).getText();
             * txt.setText(name);
             */
        }
    }
    
    private ButtonListener b = new ButtonListener();
    public Button(){
        b1.addActionListener(b);
        b2.addActionListener(b);
        this.setLayout(new FlowLayout());
        this.add(b1);
        this.add(b2);
        this.add(txt);
    }
    public static void main(String[] args) {
         SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new Button();
            }
        });
    }
}

第二種:

//直接創建ActionListener的類的對象b,使用的是匿名內部類
    private ActionListener b= new ActionListener(){// 定義內部類實現事件監聽
        public void actionPerformed(ActionEvent e) {
            txt.setText(((JButton)e.getSource()).getText()) ;
            /*
             * String name = ((JButton)e.getSource()).getText();
             * txt.setText(name);
             */
        }
        
    };

第三種:

//在程序中直接創建按鈕的監聽,不需要再引入監聽器

 
        b1.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                txt.setText(((JButton)e.getSource()).getText());
            }
        });
        b2.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                txt.setText(" ");
            }
        });

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM