做者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明。谢谢!html
在GUI中,咱们看到了如何用图形树来组织一个图形界面。然而,这样的图形界面是静态的。咱们没法互动的对该界面进行操做。GUI的图形元素须要增长事件响应(event handling),才能获得一个动态的图形化界面。java
咱们在GUI一文中提到了许多图形元素。有一些事件(Event)可能发生在这些图形元素上,好比:this
Java中的事件使用对象表示,好比ActionEvent。每一个事件有做用的图形对象,好比按钮,滚动条,菜单。spa
所谓互动的GUI,是指当上面事件发生时,会有相应的动做产生,好比:code
每一个动做都针对一个事件。咱们将动做放在一个监听器(ActionListener)中,而后让监听器监视(某个图形对象)的事件。当事件发生时,监听器中的动做随之发生。orm
所以,一个响应式的GUI是图形对象、事件对象、监听对象三者互动的结果。咱们已经知道了如何建立图形对象。咱们须要给图形对象增长监听器,并让监听器捕捉事件。htm
下面实现一个响应式的按钮。在点击按钮以后,面板的颜色会改变,以下图:对象
(这个例子改编自Core Java 2,Volume 1, Example 8-1)blog
import javax.swing.*; import java.awt.event.*; import java.awt.*; public class HelloWorldSwing { private static void createAndShowGUI() { JFrame frame = new JFrame("HelloWorld"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Pane's layout Container cp = frame.getContentPane(); cp.setLayout(new FlowLayout()); // add interactive panel to Content Pane cp.add(new ButtonPanel()); // show the window frame.pack(); frame.setVisible(true); } public static void main(String[] args) { Runnable tr = new Runnable() { public void run() { createAndShowGUI(); } }; javax.swing.SwingUtilities.invokeLater(tr); } } /** * JPanel with Event Handling */ class ButtonPanel extends JPanel { public ButtonPanel() { JButton yellowButton = new JButton("Yellow"); JButton redButton = new JButton("Red"); this.add(yellowButton); this.add(redButton); /** * register ActionListeners */ ColorAction yellowAction = new ColorAction(Color.yellow); ColorAction redAction = new ColorAction(Color.red); yellowButton.addActionListener(yellowAction); redButton.addActionListener(redAction); } /** * ActionListener as an inner class */ private class ColorAction implements ActionListener { public ColorAction(Color c) { backgroundColor = c; } /** * Actions */ public void actionPerformed(ActionEvent event) { setBackground(backgroundColor); // outer object, JPanel method repaint(); } private Color backgroundColor; } }
上面,咱们用一个内部类ColorAction来实施ActionListener接口。这样作是为了让监听器能更方便的调用图形对象的成员,好比setBackground()方法。接口
ActionListener的actionPerformed()方法必须被覆盖。该方法包含了事件的对应动做。该方法的参数为事件对象,即监听ActionEvent类型的事件。ActionEvent是一个高层的类,Java会找到图形对象(按钮)会发生的典型事件(点击)做为事件。
ColorAction生成的对象即为监听器对象。
咱们为两个按钮JButton添加了相应的监听器对象。当有事件发生时,对应动做将随之产生。
ActionListener interface
ActionEvent class