Loading new fxml in the same scene

2019-01-01 03:53发布

I have 2 fxml files:

  • Layout (header, menubars and content)
  • Anchorpane (it's supposed to be placed inside the content from the other fxml file)

I would like to know how can I load the second file inside the content space from the "Master" scene. And is that a good thing to do working in javaFX or is it better to load a new scene?

I'm trying to do something like this, but it doesn't work:

@FXML
private AnchorPane content;

@FXML
private void handleButtonAction(ActionEvent event) {        
    content = (AnchorPane) FXMLLoader.load("vista2.fxml");
}

Thanks for the help.

7条回答
旧人旧事旧时光
2楼-- · 2019-01-01 04:43

In this case, I recommend you to use custom component instead. First create a custom component for your content:

class Content2 extends AnchorPane {
    Content() {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("vista2.fxml");
        loader.setRoot(this);
        loader.setController(this);
        loader.load();
    }
}

Replace the AnchorPane markup in the root of your vista2.fxml file with fx:root:

<fx:root type="javafx.scene.layout.AnchorPane" xmlns:fx="http://javafx.com/fxml">
    ...
</fx:root>

Then, you can do this simply by using custom event binding and arrow function. Add event handler property to your Content class:

private final ObjectProperty<EventHandler<ActionEvent>> propertyOnPreviousButtonClick = new SimpleObjectProperty<EventHandler<ActionEvent>>();

@FXML
private void onPreviousButtonClick(ActionEvent event) {
    propertyOnPreviousButtonClick.get().handle(event)
}

public void setOnPreviousButtonClick(EventHandler<ActionEvent> handler) {
    propertyOnPreviousButtonClick.set(handler);
}

Finally, bind your custom event handler in your java code or fxml:

@FXML
onNextButtonClick() {
    Content2 content2 = new Content2();
    content2.setOnPreviousButtonClick((event) -> {
        Content1 content1 = new Content1();

        layout.getChildren().clear();
        layout.getChildren().add(content1);
    });

    layout.getChildren().clear();
    layout.getChildren().add(content2);    
}

If you don't want to add content dynamically, just setVisible() to true or false

查看更多
登录 后发表回答