【问题标题】:JavaFX: Remove the scene loaded in Center of BorderPaneJavaFX:删除在 BorderPane 中心加载的场景
【发布时间】:2014-01-30 15:35:30
【问题描述】:

我有一个 JavaFX2.2 应用程序,它在主屏幕上有一个 BorderPane。在顶部窗格中,我有两个按钮“按钮 A”和“按钮 B”,分别在 BorderPane 的中心动态加载场景“场景 A”和“场景 B”。

“场景 A”有两个按钮。在 FXML 文件中,其中一个定义为“默认按钮”,另一个定义为“取消按钮”。

“场景 B”有一个 TextField 和一个 TableView。

以下是从主屏幕切换场景的代码sn-p。

@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”上后点击“Enter”按钮时,会执行“场景 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 javafx-2 fxml


    【解决方案1】:

    这是known bug:当按钮不属于场景时,它不应接收事件。该错误已在 Java 8 中修复。我整理了一个简单的示例,可以确认 Java 7 中的错误以及它在 Java 8 中已修复。您可能希望在 Java 8 中运行您的代码,看看它是否有效正确的在那里。

    对于 Java 7 解决方法,将代码包装在您的 defaultButton(也可能是取消按钮)的处理程序中

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-05
      • 1970-01-01
      相关资源
      最近更新 更多