JAVA按鈕事件

不同的事件源可以產生不同類別的事件。例如,按鈕可以發送一個ActionEvent對象,而窗口可以發送WindowEvent對象。
AWT時間處理機制的概要:
1.監聽器對象是一個實現了特定監聽器接口(listener interface)的類的實例。
2.事件源是一個能夠註冊監聽器對象併發送事件對象的對象。
3.當事件發生時,事件源將事件對象傳遞給所有註冊的監聽器。
4.監聽器對象將利用事件對象中的信息決定如何對事件做出響應。

下面是監聽器的一個示例:
ActionListener listener = ...;
JButton button = new JButton("OK");
button.addActionListener(listener);
現在,只要按鈕產生了一個“動作事件”,listener對象就會得到通告。對於按鈕來說,正像我們想到的,動作事件就是點擊按鈕。

爲了實現ActionListener接口,監聽器類必須有一個被稱爲actionPerformed的方法,該方法接收一個ActionEvent對象參數。
class MyListener implements ActionListener
{
  ...;
  public void actionPerformed(ActionEvent event)
  {
     //reaction to button click goes here
  }
}
只要用戶點擊了按鈕,JButton對象就會創建一個ActionEvent對象,然後調用listener.actionPerformed(event)傳遞事件對象。可以將多個監聽器對象添加到一個像按鈕這樣的事件源中。這樣一來,只要用戶點擊按鈕,按鈕就會調用所有監聽器的actionPerformed方法。

實例:處理按鈕點擊事件
爲了加深對事件委託模型的理解,下面以一個響應按鈕點擊事件的簡單示例來說明所需要知道的細節。在這個示例中,想要在一個面板中放置三個按鈕,添加三個監聽器對象用來作爲按鈕的動作監聽器。
在這個情況下,只要用戶點擊面板上的任何一個按鈕,相關的監聽器對象就會接收到一個ActionEvent對象,它表示有個按鈕被點擊了。在示例程序中,監聽器對象將改變面板的背景顏色。
在演示如何監聽按鈕點擊事件之前,首先需要講解一下如何創建按鈕以及如何將他們添加到面板中。
可以通過在按鈕構造器中指定一個標籤字符串、一個圖標或兩項都指定來創建一個按鈕。下面是兩個示例:
JButton yellowButton = new JButton("Yellow");
JButton blueButton = new JButton(new ImageIcon("blue-ball.gif"));
將按鈕添加到面板中需要調用add方法:
JButton yellowButton = new JButton("Yellow");
JButton blueButton = new JButton("Blue");
JButton redButton = new JButton("Red");

buttonPanel.add(yellowButton);
buttonPanel.add(blueButton);
buttonPanel.add(redButton);
至此,知道了如何將按鈕添加到面板上,接下來需要增加讓面板監聽這些按鈕的代碼。這需要一個實現了ActionListener接口的類。如前所述,應該包含一個actionPerformed方法,其簽名爲:
public void actionPerformed(ActionEvent event)

當按鈕被點擊時,希望將面板的背景顏色設置爲指定的顏色。這個顏色存儲在監聽器類中:
class ColorAction implements ActionListener
{
   public ColorAction(Color c)
   {
      backgroundColor = c;
    }
    public void actionPerformed(actionEvent event)
    {
      //set panel background color
     }
     private Color backgroundColor;
}

然後,爲每種顏色構造一個對象,並將這些對象設置爲按鈕監聽器。
ColorAction yelloAction = new ColorAction(Color.YELLOW);
ColorAction blueAction = new ColorAction(Color.BLUE);
ColorAction redAction = new ColorAction(Color.RED);

yellowButton.addActionListener(yellowAction);
blueButton.addActionListener(blueAction);
redButton.addActionListener(redAction);
例如,如果一個用戶在標有“Yellow”的按鈕上點擊了一下,yellowAction對象的actionPerformed方法就會被調用。這個對象的backgroundColor實例域被設置爲Color.YELLOW,現在就將面板的背景顏色設置爲黃色。

這裏還有一個需要考慮的問題。ColorAction對象不能訪問buttonpanel變量。可以採用兩種方式解決這個問題。一個是將面板存儲在ColorAction對象中,並在ColorAction的構造器中設置它;另一個是將ColorAction作爲ButtonPanel類的內部類,如此,它的方法就自動地擁有訪問外部面板的權限了。
下面說明一下如何將ColorAction類放在ButtonFrame類內。
class ButtonFrame extends JFrame
{
  ...
  private class ColorAction implents ActionListener
  {
    ...
    public void actionPerformed(ActionEvent event)
    {
       buttonPanel.setBackground(backgroundColor);
    }
    private Color backgroundColor;
   }
   private Jpanel buttonPanel; 
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章