2

我想在我的新项目中使用 JavaFX,并想要下面的屏幕截图中的内容。

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

当我单击“安全”按钮时,它应该在右侧加载我的“安全”场景。但我怎么能做到这一点。没有找到任何解决方案。

在此处输入图像描述

非常感谢

4

1 回答 1

6

这是这种导航的示例性实现。这里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();
        }
    }
}
于 2017-12-29T13:47:06.457 回答