gpt4 book ai didi

javafx 事件不工作

转载 作者:行者123 更新时间:2023-12-01 19:53:05 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com