Java:ActionListener接口

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();
	}
}

效果图如下:

在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值