How to replace a scene component with a button click inJavaFX

2.7k views Asked by At

Am new to JavaFX and changing only a component of a scene on button click while other components of the scene remain unchanged is giving me hard times. I have a splitpane with 2 divisions. One part containing a HBox with buttons and a VBox on the other. How can I replace the VBox depending on button clicked ? thanks in advance, Below is my sample code:

public class ShoolLibrary extends Application {
    BorderPane b_pane;
    SplitPane common;
    Scene scene; 

    @Override
    public void start(Stage primaryStage) {

        primaryStage.setTitle("The Library");
        b_pane = new BorderPane();

        common = commonGround();

        b_pane.setCenter(common);

        scene = new Scene(b_pane, 700, 480);
        primaryStage.setScene(scene);

        primaryStage.show();
    } 
     //Main Content 
     private SplitPane commonGround(){
         HBox hb = new HBox(); //Holds Buttons for Action
         VBox vb = new VBox(); //This should change depending on button click

            Button btn1 = new Button("library profile");
            Button btn2 = new Button("Books");
            Button btn3 = new Button("Members");

            //Button Action
            btn1.setOnAction(actionEvent -> /*Replace vb with profile()*/);
            btn2.setOnAction(actionEvent -> /*Replace vb with books()*/);
            btn2.setOnAction(actionEvent -> /*Replace vb with members()*/));

            hb.getChildren().addAll(btn1,btn2,btn3);

            SplitPane sp = new SplitPane();
            sp.setOrientation(Orientation.HORIZONTAL);

            sp.getItems().addAll(hb,vb);

            return sp;
    }

    private VBox profile(){
         txt = new Text("Inside library profile");
            VBox vbx1 = new VBox();
            vbx1.getChildren().add(txt);
            return vbx1;
    }
    private VBox books(){
         txt = new Text("Inside books");
            VBox vbx1 = new VBox();
            vbx1.getChildren().add(txt);
            return vbx1;
    }
    private VBox members(){
         txt = new Text("Inside Members");
            VBox vbx1 = new VBox();
            vbx1.getChildren().add(txt);
            return vbx1;
    }

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

}
1

There are 1 answers

0
MrEbbinghaus On

How about using a wrapper pane in which you place your vBoxes?

Pane wrapperPane = new Pane();

sp.getItems().addAll(hb, wrapperPane);

then:

VBox library = profile()
btn1.setOnAction(actionEvent -> 
     wrapperPane.getChildren().clear(); 
     wrapperPane.getChildren().add( library );
);

VBox books = books()
btn2.setOnAction(actionEvent -> 
     wrapperPane.getChildren().clear(); 
     wrapperPane.getChildren().add( books );
);

and so on...