【发布时间】:2018-11-20 21:30:11
【问题描述】:
您好,我在处理按钮操作时遇到问题:这是我的代码:
public class HelloWorld extends Application {
Button btn;
@Override
public void start(Stage primaryStage) {
btn = new Button();
btn.setText("Say 'Hello World'");
StackPane root = new StackPane();
root.getChildren().add(btn);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
public void setButtonOnAction(EventHandler<ActionEvent> acn)
{
btn.setOnAction(acn);
}
}
我的控制器类
public class Controller {
private HelloWorld helloWorld;
private Model model;
public Controller(HelloWorld helloWorld, Model model) throws Exception {
this.helloWorld = helloWorld;
this.model = model;
System.out.println(this.mainView.returnOne());
this.helloWorld.setButtonOnAction(e->
{
System.out.println("CATCH");
});
}
}
主运行类:
public class runExample {
public static void main(String[] args) throws Exception {
HelloWorld helloWorld = new HelloWorld();
Model model = new Model();
Application.launch(helloWorld.getClass(),args);
Controller controller = new Controller(helloWorld, model);
}
}
`
有谁知道为什么 setButtonOnAction 在控制器类中不起作用,但在 HelloWorld 类中却可以完美运行?编译器不会给我任何错误。只有当我像这样切换运行类时:
Controller controller = new Controller(mainView, model);
Application.launch(mainView.getClass(),args);
它给了我
线程“主”java.lang.NullPointerException 中的异常
如果我在 HelloWorld 类中使用 setButtonOnAction,它可以正常工作。你能帮我在我的控制器类中捕捉事件吗?我正在使用 jdk8,但在 11 上它也不起作用。
【问题讨论】:
-
您创建的
HelloWorld实例与Application.launch使用的实例不同,并且Application.launch在javafx 工具包退出之前不会返回,在这种情况下是在最后一个窗口关闭之后... -
我已经修好了,谢谢。
标签: java user-interface events javafx event-handling