做者: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