动作事件处理
动作事件由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);//当用户点击窗体