JavaFX, switching panes in a root window and retaining memory

后端 未结 1 1517
一向
一向 2021-01-27 14:25

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

相关标签:
1条回答
  • 2021-01-27 14:43

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题