[英]JavaFX how to handle ActionEvent from controller class?
Hello i have problem with handling action from my button: here's my code: 您好,我无法通过按钮处理操作:这是我的代码:
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);
}
}
my controller class 我的控制器班
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");
});
}
}
main runClass: 主要runClass:
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);
}
}
` `
Does anyone know why setButtonOnAction don't work in controller class but in HelloWorld class it work perfectly ? 有谁知道为什么setButtonOnAction在控制器类中不起作用,而在HelloWorld类中却完美地起作用? Compiler don't give me any error.
编译器不会给我任何错误。 Only if i switch in run class like that:
只有当我像这样切换运行类时:
Controller controller = new Controller(mainView, model);
Application.launch(mainView.getClass(),args);
it gives me 它给我
Exception in thread "main" java.lang.NullPointerException
线程“主”中的异常java.lang.NullPointerException
and if i'm using setButtonOnAction in HelloWorld class it works fine. 如果我在HelloWorld类中使用setButtonOnAction,它会正常工作。 Can u help me catch event in my controller class ?
您可以帮助我在控制器类中捕获事件吗? I'm using jdk8 but on 11 it isn't work too.
我正在使用jdk8,但在11上它也不起作用。
Working example ;) 工作示例;)
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);
Controller controller = new Controller(this,new Model()));
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
public void setButtonOnAction(EventHandler<ActionEvent> acn)
{
btn.setOnAction(acn);
}
}
And run class: 并运行类:
public class runExample {
public static void main(String[] args) throws Exception {
Application.launch(HelloWorld.class,args);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.