JAVA中ActionEvent不使用内部类

本文主要展示了如何为按钮添加事件监听,并通过事件源对象确定事件触发的按钮,进而改变容器的背景颜色。

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

This program shows mainly how to add the events to the buttons. Normally we use the internal class, but this example does not use it. Instead, it uses a bloc "actionPerformed" that enables a couple of buttons to call it. To determine on which button the action event occurred, we use e.getSource().

package com.han; import java.awt.*; import java.awt.event.*; import javax.swing.JFrame; /** * This program shows mainly how to add the events to the buttons. * Normally we use the internal class, but this example does not use it. * Instead, it uses a bloc "actionPerformed" that enables a couple of buttons to call it. * To determine on which button the action event occurred, we use e.getSource(). * @author han * */ @SuppressWarnings("serial") public class SwingButtonEvents extends JFrame implements ActionListener{ /*declare some variables*/ Button btn1; Button btn2; Button btn3; Container c=getContentPane(); /*the construct function*/ public SwingButtonEvents(){ setTitle("Action Event"); setSize(200,150); setVisible(true); setDefaultCloseOperation(EXIT_ON_CLOSE); c.setLayout(new FlowLayout(FlowLayout.CENTER)); //use FlowLayout btn1=new Button("Yellow"); btn2=new Button("Green"); btn3=new Button("Exit"); c.add(btn1); c.add(btn2); c.add(btn3); btn1.addActionListener(this); // 把事件聆听者向btn1注册 btn2.addActionListener(this); // 把事件聆听者向btn2注册 btn3.addActionListener(this); // 把事件聆听者向btn3注册 } public static void main(String args[]){ new SwingButtonEvents(); } @Override public void actionPerformed(ActionEvent e){ //方法重写 Button btn=(Button) e.getSource(); // 取得事件源对象 if(btn.equals(btn1)){ // 如果是按下btn1按钮 c.setBackground(Color.yellow); //背景颜色是在Container中改的!而不是在JFrame中改! }else if(btn==btn2){ // 如果是按下btn2按钮 c.setBackground(Color.green); }else{ // 如果是按下btn3按钮 System.exit(0); } } }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值