java事务实例--处理按钮点击事件

AWT事件处理机制概要(来自白书):

1.事件监听器是一个实现了监听器接口的类实例。
2.事件源对象能够注册监听器并向其发送事件对象。
3.当事件发生时事件源将事件对象发送给所有注册的监听器。
4.监听器对象再使用事件对象中的信息决定如何对事件做出响应。

现在来看一个具体案例,当用户点击按钮,JButton对象创建一个ActionEvent对象,再调用Listener.actionPerformed(event)。
简单来说就是: 点即按钮->调用该按钮所有监听器的actionPerformed方法。

下面就是一个点击相应颜色按钮将面板调整为对应颜色的事件。

在这里插入图片描述在这里插入图片描述

package Frame;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ButtonFrame extends JFrame {

	private JPanel buttonPanel;
	private static final int DEFAULT_WIDTH=300;
	private static final int DEFAULT_HEIGHT=200;
	
	public static void main(String[] args)
	{
		EventQueue.invokeLater(()->
		{
			var button=new ButtonFrame();
			button.setVisible(true);
			button.setTitle("button");
		});
	}
	
	public ButtonFrame()
	{
		setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);
		
		var yellowButton=new JButton("Yellow");
		var greenButton=new JButton("Green");
		var blueButton=new JButton("Blue");
		var redButton = new JButton("Red");
		
		buttonPanel = new JPanel();
		
		buttonPanel.add(yellowButton);
		buttonPanel.add(blueButton);
		buttonPanel.add(redButton);
		buttonPanel.add(greenButton);
		
		add(buttonPanel);
		
		var yellowAction=new ColorAction(Color.YELLOW);
		var greenAction=new ColorAction(Color.GREEN);
		var redAction=new ColorAction(Color.RED);
		var blueAction=new ColorAction(Color.BLUE);
		
		yellowButton.addActionListener(yellowAction);
		blueButton.addActionListener(blueAction);
		redButton.addActionListener(redAction);
		greenButton.addActionListener(greenAction);
		
		
		
	}
	
	private class ColorAction implements ActionListener {//为了使ColorAction对象访问buttonPanel对象,使用了内部类实现
		
		private Color backgroundColor;
		
		public ColorAction(Color c)
		{
			backgroundColor=c;
		}
		
		public void actionPerformed(ActionEvent event)
		{
			buttonPanel.setBackground(backgroundColor);
		}

	}
	
}

  • 7
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

_Rikka_

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

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

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

打赏作者

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

抵扣说明:

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

余额充值