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("你點擊了按鈕");
}
});
}
}