SplitPane中的JavaFX切换场景?

时间:2015-11-22 23:39:22

标签: java javafx javafx-8

在Base我有一个AnchorPane然后是一个SplitPane。在左侧窗格中,我有一个listView,根据所选的列表元素,右侧窗格显示相应的内容。我这样做的方法是重叠AnchorPanes并最初将它们设置为.setVisible(false),当它们被选中时,我将它们设置为.setVisible(true),如下所示:

public void listSelection() {       
    String selection = listView.getSelectionModel().getSelectedItem();
    switch(selection) {
    case "Speed of sound":
        disableOld(); // disables old AnchorePane
        response.setText("Speed of sound conversion");
        AnchorPane1.setVisible(true);   
        break;
    case "Temperature conversion":
        disableOld(); 
        response.setText("Temperature conversion");
        AnchorPane2.setVisible(true);       
        break;
    }
}

我想知道如何在视觉上产生相同的效果,但是我想为每个新的AnchorPane提供不同的场景,让它拥有自己的FXML和ControllerClass。

1 个答案:

答案 0 :(得分:2)

  

您可以实现以下内容:

您的主要班级:

public void start(Stage primaryStage) throws IOException {
            primaryStage.setTitle("Title");
            primaryStage.setScene(createScene(loadMainPane("path_of_your_fxml")));
            primaryStage.show();

    }

    private Pane loadMainPane(String path) throws IOException {
        FXMLLoader loader = new FXMLLoader();

        Pane mainPane = (Pane) loader.load(
                getClass().getResourceAsStream(path));

        return mainPane;
    }


    private Scene createScene(Pane mainPane) {
        Scene scene = new Scene(mainPane);
      return scene;
    }
    public static void main(String[] args) {launch(args); }

然后您可以创建单独的类调用Navigator来存储所有fxml路径:

public class Navigator {

private final String P1;
private final String P2;
//then you can implement getters...
public String getP1() {
    return P1;
}

public String getP2() {
    return p2;
}

private static FxmlController Controller;

    public static void loadPane(String fxml) {
    try {
        FxmlController.setPane(
                (Node) FXMLLoader.load(Navigator.class.getResource(fxml)));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public Navigator() throws IOException {
    this.P1 = "p1.fxml";
    this.P2 = "p2.fxml";}

在您的主FxmlController(应用程序的永久层的控制器,其余的堆栈窗格 - {p1和p2}将加载到您的永久层上)

这是您在主FxmlController上加载图层的方式:

@FXML
private StackPane stackPaneHolder;
... 

public void setPane(Node node) {
    if (stackPaneHolder.getChildren().isEmpty()) {
        //if stackPaneHolder is empty
        stackPaneHolder.getChildren().add(node);

    } else {
        if (stackPaneHolder.getClip() != node) {
          //if stackPaneHolder is not empty then remove existing layer and add new layer
            stackPaneHolder.getChildren().remove(0);
            stackPaneHolder.getChildren().add(0, node);
        }
    }
}

然后您可以按下如下按钮来加载窗格:

@FXML
private void btnAction(ActionEvent event) throws IOException {
Navigator.load(new Navigator().getP1());
..

这是它的工作原理: enter image description here