j2se使用ActionListener实现界面上按钮点击的事件监听操作

public class my_eventListener extends JFrame implements ActionListener {
//实现接口,要实现所有接口里的方法。
	//定义一个panel
	JPanel mp = null;
	//两个按钮,作为按钮类监听的事件源,而my_eventListener来监听事件,实现一个监听接口
	JButton jb1 = new JButton("按钮1");
	JButton jb2 = new JButton("按钮2");
	
	public static void main(String[] args) {
		my_eventListener my = new my_eventListener();
	}
	
	//构造函数
	public my_eventListener(){
		mp = new JPanel();
		
		this.add(jb1,BorderLayout.NORTH);
		mp.setBackground(Color.black);
		this.add(mp);
		this.add(jb2,BorderLayout.SOUTH);
		
		//注册监听,给按钮jb1注册一个在JFrame上的监听。也可以注册其他的class。
		jb1.addActionListener(this);
		//指定action命令,当点击jb1时,传递命令black
		jb1.setActionCommand("black");
		
		jb2.addActionListener(this);
		jb2.setActionCommand("red");
		this.setSize(200,150);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setVisible(true);
}

	//对事件处理的方法或操作
	@Override
	public void actionPerformed(ActionEvent e) {
		//判断哪个按钮被点击
		if(e.getActionCommand().equals("black")){
			System.out.println("点击了black");
		}
		if(e.getActionCommand().equals("red")){
			System.out.println("点击了red");
		}
	}


}

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

你说我听海绵宝宝派大星

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值