Java-ActionEvent事件

本文介绍了一个使用Java Swing的ActionListener接口实现按钮点击事件处理的例子。通过这个简单的示例,展示了如何为按钮设置监听器,并在按钮被点击时改变窗口背景颜色。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需要设计一个ActionListener 的接口

package Test;

import java.awt.*;
import java.awt.event.*;

class ColorAction implements ActionListener{
	private ActionExample frame; //用主类对象作为对象。翻遍两类之间联系
	private Color bgColor;
	public ColorAction(ActionExample btn,Color c){//带两个参数构造方法
		frame = btn;
		bgColor = c;
	}
	
	public void actionPerformed(ActionEvent e){
		frame.setBackground(bgColor);
	}
}

public class ActionExample extends Frame {
	
	ActionExample() {       ///构造函数
		// TODO Auto-generated constructor stub
		Panel panel = new Panel();
		Button redButton = new Button("红色");
		panel.add(redButton);
		add(panel, "South");
		//注册时间侦听器,同一个类的三个不同对象
		redButton.addActionListener(new ColorAction(this, Color.red));
	}
	
	public static void main(String argc[]){
		ActionExample myframe = new ActionExample();
		myframe.setBounds(500, 400, 300, 200);
		myframe.setVisible(true);
		myframe.addWindowListener(new WindowAdapter() {  //窗口体关闭
			public void windowClosing(WindowEvent e){
				System.exit(0);
			}
		});
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值