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

标签 java javafx eventhandler

我正在尝试注册我的按钮,但我不知道该怎么做,我创建了一个嵌套类 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);
}

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

最佳答案

当您说“不起作用”时,不确定您的错误是什么。下面是简单快速的工作演示。你弄清楚自己错在哪里。

注意:如果内部类的唯一目的是定义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");
        }
    }

}

关于java - 如何注册按钮处理程序(嵌套类),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58369071/

相关文章:

java - 启动 Neo4j 失败 : Component was successfully initialized, 但未能启动

java - 如何在 JavaFX 中使用 jFrames?

java - 如何以左右水平可导航样式显示小图片图标库,就像在 JavaScript/JQuery 中一样

Javascript button.onclick 没有像我想象的那样运行

c# - 举行事件触发了两次Windows Phone 8.1

带有回车符和换行符的javascript错误

java - 运行 chat.xhtml 示例返回 : Info: WebSocket closed

java - 远程主机上的 Selenium 2.0 机器人类

JavaFX Maven jfx :jar error: Could not find artifact javafx-packager

JavaFX EventHandler 传递参数