首先明确几个概念
1。事件源:如Button等可以产生时间,不同事件源产生不同的事件对象,例如JButton产生ActionEvent对象,而窗口产生 windowEvent对象。
2。监听器,是一个实现了某种监听接口的类对象,
3。实现监听器,并且令事件源向监听器注册,然后当事件源产生事件时,事件就会被监听器捕获,进而处理事件。
一个例子:
ActionListener listener=....; //某一监听器的对象
JButton button=new JButton("ok");
button.addActionListener(listener) //事件源Button 向监听器注册
4 .如何实现一个监听器:
定义一个类,实现一个监听接口如:ActionListener, 然后实现接口中的方法:actionPerformed();
eg. class MyListener implements ActionListener
{
public void actionPerformed()
{
方法体...............
}
}
5,一个实例:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ActionTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
ActionFrame frame = new ActionFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class ActionFrame extends JFrame
{
private JPanel buttonPanel;
public ActionFrame()
{
setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);
buttonPanel=new JPanel();
add(buttonPanel);
JButton button=new JButton("red");
buttonPanel.add(button);
button.addActionListener(new ColorAction(Color.RED));
}
public class ColorAction implements ActionListener //开发人员只需为此抽象类创建子类并定义 actionPerformed 方法即可。
{
/**
* Constructs a color action.
* @param name the name to show on the button
* @param icon the icon to display on the button
* @param c the background color
*/
Color color;
public ColorAction(Color name)
{
color=name;
}
public void actionPerformed(ActionEvent event)
{
buttonPanel.setBackground(color);
}
}
public static final int DEFAULT_WIDTH = 300;
public static final int DEFAULT_HEIGHT = 200;
}