[英]javafx events not working
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);
}
}
現在此代碼不起作用。 請幫忙。 請注意:如果有人有另一個封裝事件處理程序的想法,那么請盡可能提及它,因為我的目標是在一個類中定義事件處理程序並在另一個類中注冊它。 謝謝。
當然,這是行不通的,您每次調用button1()
和button2()
都在創建Button
的實例。 HBox
中的button1
和button2
實例與您添加事件處理程序的實例不同。
我絕對建議不要像您所做的那樣分裂。 這種拆分使解決問題變得很困難,並且無論何時調用這些方法中的任何一個,都在創建新實例。 堅持原來的做法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.