在java中,都将事件的相关信息封装在一个事件对象中,所有的事件对象都最终派生于java.util.EventObje
类。当然,每个事件类型还有子类,例如ActionEvent和WindowEvent。不同的事件源可以产生不同类别
的事件。例如,按钮可以发送一个ActionEvent对象,而窗口可以发送WindowEvent对象。
下面以一个响应按钮点击事件简单示例来说明所需要知道的所有细节。在这个示例中,想要在一个面板中
放置三个按钮,添加三个监听器对象用来作为按钮的动作监听器。只要用户点击面板上的任何一个按钮,
相关的监听器对象就会接收到一个Action Event对象,他表示有个按钮被点击了。在示例程序中,监听器
对象将改变面板的背景颜色。
- import java.awt.*;
- import java.awt.event.*;
- import javax.swing.*;
- public class Main {
- public static void main(String[] args)
- {
- EventQueue.invokeLater(()->{
- JFrame frame=new ButtonFrame();
- frame.setTitle("ListenerTest");
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- frame.setVisible(true);
- }
- );
- }
- }
- class ButtonFrame extends JFrame {
- private JPanel buttonPanel;
- public ButtonFrame(){
- setSize(300,200);
- //create buttons
- JButton yellowButton = new JButton("Yellow");
- JButton blueButton=new JButton("Blue");
- JButton redButton=new JButton("Red");
- /*
- 由于不能将组件加入到JFrame中,我们使用JPanel(一个面板容器类,可以放按钮、图片、标签等)作为中间容器,
- 然后再将JPanel置为JFrame的内容
- */
- buttonPanel=new JPanel();
- //add buttons to panel
- buttonPanel.add(yellowButton);
- buttonPanel.add(blueButton);
- buttonPanel.add(redButton);
- //add panel to frame
- add(buttonPanel);
- //create button actions
- ColorAction yellowAction = new ColorAction(Color.YELLOW);
- ColorAction blueAction = new ColorAction(Color.BLUE);
- ColorAction redAction = new ColorAction(Color.RED);
- //associate actions with buttons
- yellowButton.addActionListener(yellowAction);
- blueButton.addActionListener(blueAction);
- redButton.addActionListener(redAction);
- }
- //当按钮被点击时,将面板的颜色设置为指定的颜色,这个颜色存储在监听器类中
- private class ColorAction implements ActionListener{
- private Color backgroundColor;
- public ColorAction(Color c){
- backgroundColor = c;
- }
- public void actionPerformed(ActionEvent event){
- //ActionEvent对应按钮点击、菜单选择、选择列表项或在文本框中ENTER
- buttonPanel.setBackground((backgroundColor));
- }
- }
- }
方法就会被调用。这个对象的backgroundColor实例域被设置为Color.YELLOW,现在就将面板的背景色设
置为黄色了