跳轉到內容

事件監聽器

75% developed
來自華夏公益教科書,開放的書籍,用於開放的世界

導航 使用者介面 主題:v  d  e )


事件監聽器一旦設定到小程式物件,就會等待對它執行一些操作,無論是滑鼠點選、滑鼠懸停、按鍵按下、按鈕點選等。您正在使用的類(例如 JButton 等)會將活動報告給使用它的類設定的類。然後,該方法決定如何對該操作做出反應,通常使用一系列 if 語句來確定執行的是哪個操作。source.getSource() 將返回執行事件的物件的名稱,而 source 是在執行操作時傳遞給函式的物件。每次執行操作時,都會呼叫該方法。

ActionListener

[編輯 | 編輯原始碼]

ActionListener 是一個介面,可以實現它來確定如何處理特定事件。實現介面時,應該實現該介面中的所有方法,ActionListener 介面有一個要實現的方法,名為 actionPerformed()

程式碼清單 9.6 顯示瞭如何實現 ActionListener

Computer code 程式碼清單 9.6:EventApplet.java
import java.applet.Applet;
import java.awt.Button;
import java.awt.Container;
import java.awt.Dialog;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class EventApplet extends Applet {

    /**
     * Init.
     */
    public void init() {
        Button clickMeButton = new Button("Click me");

        final Applet eventApplet = this;

        ActionListener specificClassToPerformButtonAction = new ActionListener() {

            public void actionPerformed(ActionEvent event) {
                Dialog dialog = new Dialog(getParentFrame(eventApplet), false);
                dialog.setLayout(new FlowLayout());
                dialog.add(new Label("Hi!!!"));
                dialog.pack();
                dialog.setLocation(100, 100);
                dialog.setVisible(true);
            }

            private Frame getParentFrame(Container container) {
                if (container == null) {
                    return null;
                } else if (container instanceof Frame) {
                    return (Frame) container;
                } else {
                    return getParentFrame(container.getParent());
                }

            }
        };
        clickMeButton.addActionListener(specificClassToPerformButtonAction);

        add(clickMeButton);
    }
}

編譯並執行上面的程式碼時,當您點選按鈕時,將出現訊息“Hi!!!”。

MouseListener

[編輯 | 編輯原始碼]

小程式滑鼠監聽器通常與 AWT 滑鼠監聽器沒有區別。當滑鼠位於小程式區域時,監聽器會收到有關滑鼠點選和拖動(如果註冊了 MouseListener)以及滑鼠移動(如果註冊了 MouseMotionListener)的通知。由於小程式通常很小,因此讓小程式本身來實現滑鼠監聽器是一種常見的做法。


Clipboard

待辦事項
新增一些練習,比如 變數 中的練習。

華夏公益教科書