不同的事件源可以產生不同類別的事件。例如,按鈕可以發送一個ActionEvent對象,而窗口可以發送WindowEvent對象。
AWT時間處理機制的概要:
1. 監聽器對象是一個實現了特定監聽器接口(listener interface)的類的實例。
2. 事件源是一個能夠注冊監聽器對象并發送事件對象的對象。
3. 當事件發生時,事件源將事件對象傳遞給所有注冊的監聽器。
4. 監聽器對象將利用事件對象中的信息決定如何對事件做出響應。
下面是監聽器的一個示例:
1
2
3
|
ActionListener listener = ...; JButton button = new JButton( "OK" ); button.addActionListener(listener); |
現在,只要按鈕產生了一個“動作事件”,listener對象就會得到通告。對于按鈕來說,正像我們想到的,動作事件就是點擊按鈕。
為了實現ActionListener接口,監聽器類必須有一個被稱為actionPerformed的方法,該方法接收一個ActionEvent對象參數。
1
2
3
4
5
6
7
8
|
class MyListener implements ActionListener { ...; public void actionPerformed(ActionEvent event) { //reaction to button click goes here } } |
只要用戶點擊了按鈕,JButton對象就會創建一個ActionEvent對象,然后調用listener.actionPerformed(event)傳遞事件對象。可以將多個監聽器對象添加到一個像按鈕這樣的事件源中。這樣一來,只要用戶點擊按鈕,按鈕就會調用所有監聽器的actionPerformed方法。
實例:處理按鈕點擊事件
為了加深對事件委托模型的理解,下面以一個響應按鈕點擊事件的簡單示例來說明所需要知道的細節。在這個示例中,想要在一個面板中放置三個按鈕,添加三個監聽器對象用來作為按鈕的動作監聽器。
在這個情況下,只要用戶點擊面板上的任何一個按鈕,相關的監聽器對象就會接收到一個ActionEvent對象,它表示有個按鈕被點擊了。在示例程序中,監聽器對象將改變面板的背景顏色。
在演示如何監聽按鈕點擊事件之前,首先需要講解一下如何創建按鈕以及如何將他們添加到面板中。
可以通過在按鈕構造器中指定一個標簽字符串、一個圖標或兩項都指定來創建一個按鈕。下面是兩個示例:
1
2
|
JButton yellowButton = new JButton( "Yellow" ); JButton blueButton = new JButton( new ImageIcon( "blue-ball.gif" )); |
將按鈕添加到面板中需要調用add方法:
1
2
3
4
5
6
7
|
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)
當按鈕被點擊時,希望將面板的背景顏色設置為指定的顏色。這個顏色存儲在監聽器類中:
1
2
3
4
5
6
7
8
9
10
11
12
|
class ColorAction implements ActionListener { public ColorAction(Color c) { backgroundColor = c; } public void actionPerformed(actionEvent event) { //set panel background color } private Color backgroundColor; } |
然后,為每種顏色構造一個對象,并將這些對象設置為按鈕監聽器。
1
2
3
4
5
6
7
|
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類內。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
class ButtonFrame extends JFrame { ... private class ColorAction implents ActionListener { ... public void actionPerformed(ActionEvent event) { buttonPanel.setBackground(backgroundColor); } private Color backgroundColor; } private Jpanel buttonPanel; } |
以上這篇java處理按鈕點擊事件的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。