JavaFX, switching panes in a root window and retaining memory

时光总嘲笑我的痴心妄想 提交于 2019-12-02 17:04:38

问题


As stated in the title, I have fxml files, I have a UI that is set up with three labels/buttons up top and the lower half of the window has a pane. Every time a label/button is clicked, the pane must switch to that corresponding fxml file. So in other words, the pane must always be in the same position, kind of like a tabbed layout but without tabs.

I know I can achieve this with just loading a new instance of an fxml file but, I want to avoid that because when a user click on a tab he previously was on, he should be able to see his earlier input.

I have some main.java that starts the program. Some controller.java that controls the UI when it is first loaded, and some fxml file corresponding to that initial view. How can I go about implementing this transition functionality? P.S. I am very novice at JavaFX.


回答1:


Here is a MCVE of how you can achieve it.
It can of course be implemented using FXML :

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class StageTest extends Application{

    private Pane pane1, pane2, mainPane;

    @Override
    public void start(Stage stage) throws Exception {

        stage.setTitle("Switch Panes");
        Button button1 = new Button("Show Pane 1");
        button1.setOnAction(e -> showPane1());
        Button button2 = new Button("Show Pane 2");
        button2.setOnAction(e -> showPane2());

        HBox buttonsPane = new HBox(5.);
        buttonsPane.getChildren().addAll(button1, button2);

        pane1 = getPane("PANE ONE");
        pane2 = getPane("PANE TWO");
        mainPane = new StackPane(pane1);

        BorderPane root = new BorderPane();
        root.setTop(buttonsPane);
        root.setCenter(mainPane);

        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.show();
    }


    private void showPane1() {
        mainPane.getChildren().clear();
        mainPane.getChildren().add(pane1);
    }

    private void showPane2() {
        mainPane.getChildren().clear();
        mainPane.getChildren().add(pane2);
    }

    private Pane getPane(String txt) {

        VBox pane = new VBox();
        pane.getChildren().addAll(new TextArea(txt+" add text here: "));
        return pane;
    }

    public static void main(String[] args) {
        launch(args);
    }
}


来源:https://stackoverflow.com/questions/46500165/javafx-switching-panes-in-a-root-window-and-retaining-memory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!