Java----ActionListener接口

ActionListener动作事件监听器,当你在点击按钮时希望可以实现一个操作就得用到该接口了。

ActionListener接口所在包

ActionListener接口在event包中,即在开头引入该包。

1 import java.awt.event.*;

ActionListener接口使用方法

该接口只用实现一个方法叫做actionPerformed(ActionEvent arg0)这个方法。这个方法就是你希望触发事件时程序要做什么。

1 class ButtonListener/*自定义名字*/ implements ActionListener {
2     public void actionPerformed(ActionEvent arg0) {
3         /*content*/
4     }
5 }

为该按钮添加对象:

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.*;
 5 
 6 public class example3 extends JFrame {
 7     //final static long serialVersionUID = 1L;
 8     Container container = getContentPane();
 9     JButton button = new JButton("点击我");//定义按钮类
10 
11     class ButtonListener implements ActionListener {
12         int x = 0;
13 
14         public void actionPerformed(ActionEvent arg0) {
15             example3.this.button.setText("我被点击了" + (++x) + "次");
16             example3.this.button.setFont(new Font("宋体",Font.PLAIN,25));
17         }
18     }
19 
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     }
29 
30     public static void main(String[] args)
31     {
32         new example3();
33     }
34 }

输出截图:

 

posted @ 2020-10-25 14:48  AA、  阅读(2088)  评论(0编辑  收藏  举报