天天看點

關于ActionListener的3種實作方法

java的swing中很難了解的一部分就是事件機制了下面是3種實作方法

1.正常的類實作方法,但這裡是定義了新的事件類,再在裡面定義按鈕,更正常的做法是定義按鈕和定義事件的都分開,但這樣在編寫大量的事件時明顯非常備援

import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import javax.swing.JButton; 

public class TestActionListener1 implements ActionListener { 

    public void actionPerformed(ActionEvent e) { 
        System.out.println("你點選了按鈕"); 
    } 

    public void test() { 
        JButton s_button = new JButton("按鈕"); 
        s_button.addActionListener(this); 
    } 
} 
           

2.使用内部類來完成

import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import javax.swing.JButton; 
public class TestActionListener2 { 

    public void test() { 
        JButton s_button = new JButton("按鈕"); 
        MyButtonActionListener s_listener = new MyButtonActionListener(); 
        s_button.addActionListener(s_listener); 
    } 

    private class MyButtonActionListener implements ActionListener { 
        public void actionPerformed(ActionEvent e) { 
            System.out.println("你點選了按鈕"); 
        } 
    } 
} 
           

3.更懶的方法,連名都不想命名了(反正都自己用)---内部匿名類

public class TestActionListener3 { 
    public void test() { 
        JButton s_button = new JButton("按鈕"); 
        s_button.addActionListener(new ActionListener() { 
            public void actionPerformed(ActionEvent e) { 
                System.out.println("你點選了按鈕"); 
            } 
        }); 
    } 
}