事件监听

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Test extends JFrame implements ActionListener{

	Wdmb mb=null;
	JButton an1,an2;

	public static void main(String[] args) throws Exception{

		Test lx=new Test();	
	}

	public Test(){

		mb=new Wdmb();
		an1=new JButton("红色");
		an2=new JButton("蓝色");
		Jtz jt1=new Jtz();

		this.add(an1,BorderLayout.NORTH);
		this.add(an2,BorderLayout.SOUTH);
		mb.setBackground(Color.green);
		this.add(mb);

		an1.addActionListener(this);
		an1.addActionListener(jt1);
		an1.setActionCommand("111");//区别按钮
		
		an2.addActionListener(this);
		an2.addActionListener(jt1);
		an2.setActionCommand("222");

		this.setSize(300,260);
		this.setLocation(300,280);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setVisible(true);	
	}

	public void actionPerformed(ActionEvent e){
		if(e.getActionCommand().equals("111")){
			System.out.println("红色红色");
			mb.setBackground(Color.red);
		}
		else if(e.getActionCommand().equals("222")){
			System.out.println("蓝色蓝色");
			mb.setBackground(Color.blue);
		}
	}


	class Wdmb extends JPanel{
		public void paint(Graphics g){
			super.paint(g);
		}
	}

	class Jtz implements ActionListener{
		public void actionPerformed(ActionEvent aa){
			if(aa.getActionCommand().equals("111"))
			{
				System.out.println("监听者在监听,知道你按下的是红色按钮");
			}
			else if(aa.getActionCommand().equals("222"))
			{
				System.out.println("监听者在监听,知道你按下的是蓝色按钮");
			}
		}
	}

}

初始界面

按下红色按钮后

按下蓝色按钮后

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值