JavaFX 导航栏和内容窗格

2024-01-14

我想在我的新项目中使用 JavaFX,并且想要像下面的屏幕截图所示的东西。

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

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

多谢


这是这种导航的示例性实现。这里描述的视图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();
        }
    }
}

update

这是一种直接在 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();
        }
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

JavaFX 导航栏和内容窗格 的相关文章

随机推荐