2012-10-22 28 views

回答

7

我找不到優雅的問題解決方案。但我發現這兩個選擇:

  • 獲取某個節點的窗口引用的場景

    @FXML private Button closeButton ; 
    
    public void handleCloseButton() { 
        Scene scene = closeButton.getScene(); 
        if (scene != null) { 
        Window window = scene.getWindow(); 
        if (window != null) { 
         window.hide(); 
        } 
        } 
    } 
    
  • 傳遞窗口作爲參數傳遞給控制器​​加載FXML時。

    String resource = "/modalWindow.fxml"; 
    
    URL location = getClass().getResource(resource); 
    FXMLLoader fxmlLoader = new FXMLLoader(); 
    fxmlLoader.setLocation(location); 
    fxmlLoader.setBuilderFactory(new JavaFXBuilderFactory()); 
    
    Parent root = (Parent) fxmlLoader.load(); 
    
    controller = (FormController) fxmlLoader.getController(); 
    
    dialogStage = new Stage(); 
    
    controller.setStage(dialogStage); 
    
    ... 
    

    而FormController必須實現setStage方法。

0
@FXML 
private Button closeBtn; 
Stage currentStage = (Stage)closeBtn.getScene().getWindow(); 
currentStage.close(); 

另一種方式是通過調用

定義靜態吸氣的舞臺和訪問

主類

public class Main extends Application { 
    private static Stage primaryStage; // **Declare static Stage** 

    private void setPrimaryStage(Stage stage) { 
     Main.primaryStage = stage; 
    } 

    static public Stage getPrimaryStage() { 
     return Main.primaryStage; 
    } 

    @Override 
    public void start(Stage primaryStage) throws Exception{ 
     setPrimaryStage(primaryStage); // **Set the Stage** 
     Parent root = FXMLLoader.load(getClass().getResource("sample.fxml")); 
     primaryStage.setTitle("Hello World"); 
     primaryStage.setScene(new Scene(root, 300, 275)); 
     primaryStage.show(); 
    } 
} 

現在你可以訪問此階段

Main.getPrimaryStage()

在控制器類

public class Controller { 
public void onMouseClickAction(ActionEvent e) { 
    Stage s = Main.getPrimaryStage(); 
    s.close(); 
} 
}