如何添加一个按钮到另一个类

问题描述:

我有一个叫做Restaurant的类,它有一个FXML文件,在那个类中,我有一个按钮,当它按下时打开另一个叫做tables的窗口,也有一个FXML文件,我有表格窗口中的最小化按钮。如何添加一个按钮到另一个类

我想要的是当我按表中的最小化按钮时,一个新的按钮将被添加到餐厅窗口。

但我收到一个空例外。 有人可以帮我解决这个问题。

这是我的最小化按钮的代码:

@FXML 
public void minimiza(ActionEvent event) { 
    Button Tables = new Button("Mesas"); 
    try { 
     Stage mesa = (Stage) ((Button) event.getSource()).getScene().getWindow(); 
     mesa.setIconified(true); 
     FXMLLoader loader = new FXMLLoader(); 
     RestauranteController controle = loader.getController(); 
     controle.adicionaBotao(Tables); 
    } catch (Exception e) { 
     System.out.println("Not working " + e.getMessage()); 
    } 
} 

这可能是从Restaurant类更好地只听Stageiconified财产。如果最小化状态iconified状态不匹配,您可以自己在控制器中为tables窗口创建此属性。

private int windowCount; 

@Override 
public void start(Stage primaryStage) { 

    Button btn = new Button("Show new Window"); 
    VBox buttonContainer = new VBox(btn); 

    btn.setOnAction((ActionEvent event) -> { 
     // create new window 
     windowCount++; 
     Label label = new Label("Window No " + windowCount); 
     Stage stage = new Stage(); 
     Scene scene = new Scene(label); 
     stage.setScene(scene); 

     // button for restoring from main scene 
     Button restoreButton = new Button("Restore Window " + windowCount); 

     // restore window on button click 
     restoreButton.setOnAction(evt -> { 
      stage.setIconified(false); 
     }); 

     // we rely on the minimize button of the stage here 

     // listen to the iconified state to add/remove button form main window 
     stage.iconifiedProperty().addListener((observable, oldValue, newValue) -> { 
      if (newValue) { 
       buttonContainer.getChildren().add(restoreButton); 
      } else { 
       buttonContainer.getChildren().remove(restoreButton); 
      } 
     }); 
     stage.show(); 
    }); 


    Scene scene = new Scene(buttonContainer, 200, 200); 

    primaryStage.setScene(scene); 
    primaryStage.show(); 
} 

BTW:注意,如果没有加载FXML,FXMLLoader绝不会创建一个控制器实例,更别说没有被指定的FXML。此外,在任何情况下,它都不会返回与您的Restaurant窗口中使用的控制器实例相同的控制器实例。

+0

它工作得很好!谢谢F* –