GUI编程基础学习(七)——动作事件、鼠标事件、键盘事件

动作事件处理

动作事件由ActionEvent类定义,最常用的是点击按钮后产生动作事件,可以通过实现ActionListener接口处理相应的动作事件;

ActionListener接口只有一个抽象方法,将在动作发生后触发,ActionListener接口的具体定义如下:

public interface ActionListener extends EventListener{
    public void actionPerformed(ActionEvent e);
}

实现接口ActionListener的类必须给出抽象方法actionPerformed()的方法体;

案例:点击颜色按钮,改变背景颜色

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;


public class Client extends JFrame implements ActionListener{

	JPanel centerPanel = new JPanel();
	JPanel bottomPanel = new JPanel();
	JButton blueButton = new JButton("蓝");
	JButton redButton = new JButton("红");
	
	public Client(){
		setTitle("动作事件案例");
		Container container = this.getContentPane();//获取窗体内置面板
		container.setLayout(new BorderLayout());//设置边界布局
		centerPanel.setPreferredSize(new Dimension(320,240));//设置面板大小
		bottomPanel.setLayout(new FlowLayout());//设置流布局
		blueButton.addActionListener(this);//添加监听
		redButton.addActionListener(this);//添加监听
		bottomPanel.add(blueButton);//向面板中添加按钮
		bottomPanel.add(redButton);
		container.add(centerPanel,BorderLayout.CENTER);//将面板添加进窗体内置面板
		container.add(bottomPanel,BorderLayout.SOUTH);
		pack();//窗体大小自适应
		setVisible(true);//展示窗体
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//当用户点击窗体
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值