java中action事件_Java-ActionEvent事件

这篇博客展示了如何在Java GUI中使用ActionListener接口来实现按钮点击事件,改变窗体背景颜色。ActionExample类继承了Frame,并在构造函数中注册了一个监听器,当用户点击红色按钮时,背景色会变为红色。此外,窗体还添加了窗口关闭监听器,调用System.exit(0)关闭程序。
摘要由CSDN通过智能技术生成

需要设计一个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);

}

});

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值