您好,我无法通过按钮处理操作:这是我的代码:
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");
});
}
}
主要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);
}
}
`
有人知道为什么setButtonOnAction在控制器类中不起作用,而在HelloWorld类中却完美地起作用吗?编译器不会给我任何错误。只有当我这样切换运行类时:
Controller controller = new Controller(mainView, model);
Application.launch(mainView.getClass(),args);
它给了我
线程“ main”中的异常java.lang.NullPointerException
,如果我在HelloWorld类中使用setButtonOnAction,它可以正常工作。您可以帮助我在控制器类中捕获事件吗?我正在使用jdk8,但在11上它也不起作用。
答案 0 :(得分:0)
工作示例;)
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);
}
}
并运行课程:
public class runExample {
public static void main(String[] args) throws Exception {
Application.launch(HelloWorld.class,args);
}
}