簡體   English   中英

JavaFX:刪除BorderPane中心中加載的場景

[英]JavaFX: Remove the scene loaded in Center of BorderPane

我有一個JavaFX2.2應用程序,它在主屏幕上有一個BorderPane。 在頂部窗格中,我有兩個按鈕“按鈕A”和“按鈕B”,分別在BorderPane的中心動態加載場景“場景A”和“場景B”。

'場景A'有兩個按鈕。 其中一個在FXML文件中定義為“默認按鈕”,另一個定義為“取消按鈕”。

'Scene B'有一個TextField和一個TableView。

以下是主屏幕中用於在場景之間切換的代碼片段。

@FXML
private void handlebtnAAction(ActionEvent event) {
    loadCentreScene("fxml/FXSceneA.fxml");       
}

@FXML
private void handlebtnBAction(ActionEvent event) {
    LoadCentreScene("fxml/FXSceneB.fxml");
}


private void loadCentreScene(String fxmlPath){
    try {
        FXMLLoader loader = new FXMLLoader(Admin.class.getResource(fxmlPath));
        AnchorPane page = (AnchorPane) loader.load();
        Plugin fxController = loader.getController();
        fxController.setMainController(this);
        Node node = getRootLayout().getCenter();
        node = null;            
        getRootLayout().setCenter(page);            
    } catch (IOException ex) {
        Dialogs.showErrorDialog(primaryStage, ex.getMessage(), "Loading Error");
    }
}

現在當我將'場景A'切換到'場景B'並在將TextField聚焦到'場景B'后點擊'輸入'按鈕時,執行“場景A”上默認按鈕的事件處理程序。

我也嘗試了以下變化,但我仍然面臨同樣的問題。

    private void loadCentreScene(String fxmlPath){
    try {
        FXMLLoader loader = new FXMLLoader(Admin.class.getResource(fxmlPath));
        AnchorPane page = (AnchorPane) loader.load();
        Plugin fxController = loader.getController();
        fxController.setMainController(this);
        Node node = getRootLayout().getCenter();
        getRootLayout().getChildren().remove(node); //<****Remove the node from children****>
        getRootLayout().setCenter(null); //<****Set center to null****>
        node = null;            
        getRootLayout().setCenter(page);            
    } catch (IOException ex) {
        Dialogs.showErrorDialog(primaryStage, ex.getMessage(), "Loading Error");
    }
}

根據我的理解,該對象應該是無法訪問的,以后應該收集垃圾。 任何人都可以幫助我理解為什么“場景A”的對象仍然可以訪問以及為什么要為默認按鈕調用事件處理程序。

這是一個已知的錯誤 :當按鈕不是場景的一部分時,按鈕不應該接收事件。 這個錯誤在Java 8中得到了修復。我把它的一個快速示例匯總在一起,並且可以確認Java 7中的錯誤並且它已在Java 8中修復。您可能希望在Java 8中運行代碼並查看它是否有效正確的。

對於Java 7的變通方法,請將代碼包裝在defaultButton的處理程序中(也可能是取消按鈕)

if (button.getScene() != null) {
  //...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM