javafx 事件不工作

标签 java events javafx

public class Testing extends Application {



    @Override
    public void start(Stage stage) 
    {

        Button button1 = new Button("First button");

        Button button2 = new Button("Second button");

        EventHandler<ActionEvent> aHandler = new EventHandler<ActionEvent>(){
            @Override
            public void handle(ActionEvent event)
            {
                button2.setText("Working");
            }
        };


        button1.addEventHandler(ActionEvent.ACTION, aHandler);

        HBox hbox = new HBox(40,button1, button2);
        Scene scene = new Scene(hbox, 840, 400);                
        stage.setScene(scene);
        stage.setTitle("Testing");
        stage.show();

    }

    public static void main(String[] args)
    {
        launch(args);
    }
}

您可以看到这是一个 javafx 测试类,我正在其中测试 eventHandlers,它工作正常,但是当我拆分代码并将其添加到它自己的方法中时,eventHandlers 不会像下面的代码那样工作

public class Testing extends Application {



    @Override
    public void start(Stage stage) 
    {

        EventHandler<ActionEvent> aHandler = new EventHandler<ActionEvent>(){
            @Override
            public void handle(ActionEvent event)
            {
                button2().setText("Working");
            }
        };
        button1().addEventHandler(ActionEvent.ACTION, aHandler);


        stage.setScene(scene());
        stage.setTitle("Testing");
        stage.show();

    }

    public Button button1()
    {
        Button btn = new Button("First button");
        return btn;     
    }


    public Button button2()
    {
        Button btn = new Button("Second button");
        return btn;
    }



    public HBox hbox()
    {
        HBox hbox = new HBox(40,button1(), button2());
        return hbox;
    }

    public Scene scene()
    {
        Scene scene = new Scene(hbox(), 840, 400);

        return scene;
    }


    public static void main(String[] args)
    {
        launch(args);
    }
}

现在这段代码不起作用。请帮忙。 请注意:如果任何人有封装 eventHandler 的其他想法,请尽可能提及,因为我的目标是在一个类中定义 eventHandler 并将其注册到另一个类中。 谢谢。

最佳答案

当然它不起作用,每次调用 button1()button2() 时,您都会创建一个 Button 实例。 HBox 中的 button1button2 实例与您添加事件处理程序的实例不同。

我绝对建议不要像你正在做的那样 split 。这种拆分使得解决问题变得困难,并且每当您调用任何这些方法时都会创建新实例。坚持你原来所做的事情。

关于javafx 事件不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50615627/

相关文章:

java - CSV 阅读器不注册更改

javafx - 需要从高度图创建三角形网格的帮助(JavaFX)

java - 我应该尽可能使用并行流吗?

java - 我的 for 循环不会重新运行 in.nextLine 的输入?

jquery - 显示从无更改为阻止时的事件监听器

jquery - 使用 jQuery 将函数惰性绑定(bind)到多个事件

javafx 变量在两个 Controller 之间传输数据(在不同 Controller 中设置和获取数据)- 已更新

java - ARToolKit:在移动设备上处理自然特征跟踪图像 (jpeg)

java - 尝试检测 Java 字节码时堆栈中的参数数量错误

java - 我如何模拟事件处理程序?