在GUI中,我們看到了如何用圖形樹來組織一個圖形界面。然而,這樣的圖形界面是靜態的。我們無法互動的對該界面進行操作。GUI的圖形元素需要增加事件響應(event handling),才能得到一個動態的圖形化界面。

我們在GUI一文中提到了許多圖形元素。有一些事件(Event)可能發生在這些圖形元素上,比如:
點擊按鈕
拖動滾動條
選擇菜單
Java中的事件使用對象表示,比如ActionEvent。每個事件有作用的圖形對象,比如按鈕,滾動條,菜單。
所謂互動的GUI,是指當上面事件發生時,會有相應的動作產生,比如:
改變顏色
改變窗口內容
彈出菜單
每個動作都針對一個事件。我們將動作放在一個監聽器(ActionListener)中,然後讓監聽器監視(某個圖形對象)的事件。當事件發生時,監聽器中的動作隨之發生。

因此,一個響應式的GUI是圖形對象、事件對象、監聽對象三者互動的結果。我們已經知道了如何創建圖形對象。我們需要給圖形對象增加監聽器,並讓監聽器捕捉事件。
查看本欄目
下面實現一個響應式的按鈕。在點擊按鈕之後,面板的顏色會改變,如下圖:

(這個例子改編自Core Java 2,Volume 1, Example 8-1)
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
作者:Vamei 出處:http://www.cnblogs.com/vamei