Java读书笔记12 事件处理基础

欢迎进入Java社区论坛,与200万技术人员互动交流 >>进入

3.实例:处理按钮点击事件 为了加深理解,以一个简单的例子来说明(《Core Java》书中例子)。 这个例子中:在一个面板中放置三个按钮,添加三个监听器对象用来作为按钮的动作监听器。 在这个情况下,只要用户点击面板上的任何一个按钮,相关的监听器对象就会接收到一个ActionEvent对象,它表示有个按钮被点击了。在示例程序中,监听器对象将改变面板的背景颜色。 具体流程如下: 1.创建按钮JButton,将按钮添加到面板中(在面板中调用add方法); 2.需要一个实现了ActionListerner接口的类(事件监听器类),它应该包含一个actionPerformed方法,其签名为: public void actionPerformed(ActionEvent event); 当按钮被点击时,我们希望将面板的背景颜色设置为指定的颜色。该颜色存储在监听器类中。 3.为每种颜色构造一个监听器对象,将这些对象设置为按钮监听器,即,调用按钮的addActionListener方法注册监听器。 代码如下: 例8-1 ButtonTest /** @version 1.32 2004-05-04 @author Cay Horstmann*/import java.awt.*;import java.awt.event.*;import javax.swing.*;public class ButtonTest{ public static void main(String[] args) { ButtonFrame frame = new ButtonFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }}/** A frame with a button panel*/class ButtonFrame extends JFrame{ public ButtonFrame() { setTitle(“ButtonTest”); setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); // add panel to frame ButtonPanel panel = new ButtonPanel(); add(panel); } public static final int DEFAULT_WIDTH = 300; public static final int DEFAULT_HEIGHT = 200; }/** A panel with three buttons.*/class ButtonPanel extends JPanel{ public ButtonPanel() { // create buttons JButton yellowButton = new JButton(“Yellow”); JButton blueButton = new JButton(“Blue”); JButton redButton = new JButton(“Red”); // add buttons to panel add(yellowButton); add(blueButton); add(redButton); // 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); } /** An action listener that sets the panel’s background color. */ private class ColorAction implements ActionListener { public ColorAction(Color c) { backgroundColor = c; } public void actionPerformed(ActionEvent event) { setBackground(backgroundColor); } private Color backgroundColor; }} 例如,如果有一个用户在标有“Yellow”的按钮上点击了一下,那么yellowAction对象的actionPerformed方法就会被调用。这个对象的backgroudColor实例域设置为Color.YELLOW,然后就将面板的颜色设置为黄颜色了。 有一个需要考虑的问题,是ColorAction对象(监听器对象)没有权限访问panel变量。可以采用两种方式解决这个问题: 1.将面板存储在ColorAction对象中,并在ColorAction构造器中设置它; 2.将ColorAction作为ButtonPanel类的内部类。这样一来,ColorAction就自动地拥有访问外部类的权限了。 这里使用的就是第二种方法,ColorAction类中调用过了外部类ButtonPanel中的setBackground方法。这种情形十分常见,事件监听器对象通常需要执行一些对其他对象可能产生影响的操作,可以策略性地将监听器类放置在需要修改状态的那个类中。

[1][2]

我知道按攻略去旅行的人往往玩得过于按步就班,

Java读书笔记12 事件处理基础

相关文章:

你感兴趣的文章:

标签云: