ActionListener動作事件監聽器,當你在點擊按鈕時希望可以實現一個操作就得用到該接口了。
ActionListener接口所在包
ActionListener接口在event包中,即在開頭引入該包。
import java.awt.event.*;
ActionListener接口使用方法
該接口只用實現一個方法叫做actionPerformed(ActionEvent arg0)這個方法。這個方法就是你希望觸發事件時程序要做什么。
class ButtonListener/*這里你可以改名字*/ implements ActionListener {
public void actionPerformed(ActionEvent arg0) {
/*content*/
}
}
但如果只寫這一個ButtonListener類我們發現是無法在點擊按鈕時運行該方法的。呵呵,你還沒有給按鈕添加這個對象呢。記得要給按鈕添加一個ActionListener的對象,即寫如下代碼。
ButtonListener button_listener = new ButtonListener();
button.addActionListener(button_listener);
接下來如果你又想移除該對象了,就直接remove掉就行了
button.removeActionListener(button_listener);
最后再嘮叨一句,ActionListener接口不僅僅適用與點擊按鈕時觸發事件,還可以在文本框、密碼框按回車時觸發事件等等。
代碼
package technology;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyFirstActionListener extends JFrame {
final static long serialVersionUID = 1L;
Container container = getContentPane();
JButton button = new JButton("點擊我");
class ButtonListener implements ActionListener {
int x = 0;
public void actionPerformed(ActionEvent arg0) {
MyFirstActionListener.this.button.setText("我被點機了" + (++x) + "次");
}
}
public MyFirstActionListener()
{
super("JFrame窗體");
this.setBounds(200, 100, 200, 200);
button.addActionListener(new ButtonListener());
container.add(button);
this.setVisible(true);
}
public static void main(String[] args)
{
new MyFirstActionListener();
}
}
效果圖如下: