如何注册按钮处理程序(嵌套类)

问题描述 投票:0回答:1

我正在尝试注册我的按钮,但是我不知道该怎么做,我创建了一个嵌套类ButtonHandler来实现EventHandler来定义其动作。

我已经尝试了代码musicRecord.setOnAction(new ButtonHandler()); ,它似乎不起作用,我想将ButtonHandler注册到musicRecord。

    musicRecord = new Button("Create a Music Record");
private class ButtonHandler implements EventHandler<ActionEvent> {
    @Override
    public void handle(ActionEvent event) {
        Music m1 = new Music();
        m1.setTitle(titleField.getText());
        m1.setYear(Integer.parseInt(yearField.getText()));
        m1.setDescription(descField.getText());
        musicDisplay.appendText(m1.toString());
        musicList.add(m1);
}

我希望按钮在单击时能够执行事件操作。

javascript java eclipse javafx eventhandler
1个回答
0
投票

不确定当您说“不起作用”时您的错误是什么。以下是简单的快速工作演示。您找出哪里出了问题。

注意:如果内部类的唯一目的是定义handle()方法,则可以使用lambda来实现。

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.stage.Stage;

public class CustomHandlerDemo extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        StackPane root = new StackPane();
        Button button = new Button("Check");
        button.setOnAction(new ButtonHandler());

        // You can do it like this as well
        /*
        button.setOnAction(e->{
            System.out.println("Clicked 2");
        });
        */

        root.getChildren().add(button);
        Scene sc = new Scene(root, 300, 300);
        primaryStage.setScene(sc);
        primaryStage.show();
    }

    private class ButtonHandler implements EventHandler<ActionEvent>{
        @Override
        public void handle(ActionEvent event) {
            System.out.println("Clicked 1");
        }
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.