JavaFX, switching panes in a root window and retaining memory

自闭症网瘾萝莉.ら 提交于 2019-12-02 12:59:47

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