2016-12-05 74 views
0

我有一個叫做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()); 
    } 
} 

回答

0

這可能是從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

它工作得很好!謝謝Fabian –

相關問題