JavaFX导航栏和contentpane

问题描述 投票:1回答:1

我想在我的新项目中使用JavaFX,并希望在下面的屏幕截图中看到类似内容。

在左侧网站上,我需要一个导航栏,右侧是我的内容。所以,我会在左侧使用VBox,在右侧使用AnchorPane(或者更好的是ScrollPane)。

当我点击按钮“安全”时,它应该在右侧加载我的“安全”场景。但是我该如何管理呢。没有找到任何解决方案。

enter image description here

非常感谢

java javafx navigationbar contentpane
1个回答
2
投票

这是这种导航的示例性实现。这里默认加载view_1.fxml中描述的视图:

<BorderPane fx:id="mainBorderPane" fx:controller="sample.Controller" xmlns:fx="http://javafx.com/fxml">
    <left>
        <VBox spacing="5">
            <Button text="btn 1" onAction="#handleShowView1"/>
            <Button text="btn 2" onAction="#handleShowView2"/>
            <Button text="btn 3" onAction="#handleShowView3"/>
        </VBox>
    </left>
    <center>
        <fx:include source="view_1.fxml"/>
    </center>
</BorderPane>

这是控制器

public class Controller {

    @FXML
    private BorderPane mainBorderPane;

    @FXML
    private void handleShowView1(ActionEvent e) {
        loadFXML(getClass().getResource("/sample/view_1.fxml"));
    }

    @FXML
    private void handleShowView2(ActionEvent e) {
        loadFXML(getClass().getResource("/sample/view_2.fxml"));
    }

    @FXML
    private void handleShowView3(ActionEvent e) {
        loadFXML(getClass().getResource("/sample/view_3.fxml"));
    }

    private void loadFXML(URL url) {
        try {
            FXMLLoader loader = new FXMLLoader(url);
            mainBorderPane.setCenter(loader.load());
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}

更新

这是一种转换,其中视图直接列在FXML文件中

<BorderPane fx:id="mainBorderPane" fx:controller="sample.Controller" xmlns:fx="http://javafx.com/fxml">
    <left>
        <VBox spacing="5">
            <Button text="btn 1" userData="/sample/view_1.fxml" onAction="#handleShowView"/>
            <Button text="btn 2" userData="/sample/view_2.fxml" onAction="#handleShowView"/>
            <Button text="btn 3" userData="/sample/view_3.fxml" onAction="#handleShowView"/>
        </VBox>
    </left>
    <center>
        <fx:include source="view_1.fxml"/>
    </center>
</BorderPane>

和控制器

public class Controller {

    @FXML
    private BorderPane mainBorderPane;

    @FXML
    private void handleShowView(ActionEvent e) {
        String view = (String) ((Node)e.getSource()).getUserData();
        loadFXML(getClass().getResource(view));
    }

    private void loadFXML(URL url) {
        try {
            FXMLLoader loader = new FXMLLoader(url);
            mainBorderPane.setCenter(loader.load());
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.