JavaFX——添加事件


最簡單的例子:點擊按鈕在控制台打印文字。

在Java代碼中,要給按鈕添加事件,只需要調用其 setOnAction 方法,並指定事件發生時的操作即可。

package sample;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.scene.text.Font;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        StackPane root = new StackPane();
        Scene scene = new Scene(root, 400, 300);

        primaryStage.setTitle("JavaFX 學習");
        primaryStage.setScene(scene);
        primaryStage.show();

        Button button = new Button("快點我");
        button.setStyle("-fx-background-color: #ff9999; -fx-padding: 10px 20px;");
        button.setFont(new Font(16));
        button.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                System.out.println("哎呀,討厭!");
            }
        });
root.getChildren().add(button); }
public static void main(String[] args) { launch(args); } }

setOnAction 方法接收的 EventHandler 是一個函數式接口,可用 lambda 表達式替換:

button.setOnAction(event -> System.out.println("哎呀,討厭!"));

示例如下圖:

 

 


 

The End.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM