Two ways to write action event handlers in JavaFX

在 javafx.scene.control 套件路徑下,如下元件受點選都會產生動作事件(ActionEvent),

    Button/TextField/CheckBox/ComboBox/RadioButton/MenuItem/Hyperlink

可對元件註冊動作事件處理器(ActionEvent Handler),接收動作事件,進行處理。

註冊動作事件處理器有兩種寫法:

1.利用元件的.setOnAction方法註冊,寫法如下

button.setOnAction(event -> System.out.println("Button clicked!"));

或

button.setOnAction(new EventHandler<ActionEvent>() {
    @Override
    public void handle(ActionEvent event) {
        System.out.println("Button clicked!");
    }
});


2. 利用.fxml檔的元件屬性註冊,寫法如下

<Button text="Click Me" onAction="#handleButtonAction"/>

public class Controller {

    @FXML
    private void handleButtonAction(ActionEvent event) {
        System.out.println("Button clicked!");
    }
}

註: 方法前的 @ 標註旨在通知編譯器作防呆檢查,減少可能錯誤
1. @Override 標註將提醒編譯器檢查該方法簽名是否有覆蓋上一代方法
2. @FXML 標註將提醒編譯器檢查該方法或屬性是否出現於 .fxml 介面配置檔中

沒有留言:

how to call Java classes in a web page by cheerpj

🚀 在瀏覽器中直接執行 Java:CheerpJ v3 實作指南 長期以來,Java Applets 因為安全性與插件問題早已退出歷史舞台。但隨著 WebAssembly (Wasm) 技術的成熟,現在網頁安裝如下 CheerpJ v3 套件庫,就可以在瀏覽器中直接呼叫 ...

總網頁瀏覽量