该接口只用实现一个方法叫做actionPerformed(ActionEvent arg0)这个方法。这个方法就是你希望触发事件时程序要做什么。
1 class ButtonListener/*自定义名字*/ implements ActionListener {
2 public void actionPerformed(ActionEvent arg0) {
3 /*content*/
为该按钮添加对象:
1 ButtonListener button_listener = new ButtonListener();
2 button.addActionListener(button_listener);
接下来如果你又想移除该对象了,就直接remove掉就行了
1 button.removeActionListener(button_listener);
代码演示:
1 package Example;
2 import java.awt.*;
3 import java.awt.event.*;
4 import javax.swing.*;
6 public class example3 extends JFrame {
7 //final static long serialVersionUID = 1L;
8 Container container = getContentPane();
9 JButton button = new JButton("点击我");//定义按钮类
11 class ButtonListener implements ActionListener {
12 int x = 0;
14 public void actionPerformed(ActionEvent arg0) {
15 example3.this.button.setText("我被点击了" + (++x) + "次");
16 example3.this.button.setFont(new Font("宋体",Font.PLAIN,25));
17 }
18 }
20 public example3()
21 {
22 super("JFrame窗体");
23 this.setBounds(200, 100, 500, 500);
24 button.addActionListener(new ButtonListener());
25 container.add(button);
26 this.setVisible(true);
27 setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
28 }
30 public static void main(String[] args)
31 {
32 new example3();
33 }
输出截图: