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