javafx-8 - 如何在 JavaFX 中通过单击按钮替换场景组件

标签 javafx-8 splitpane borderpane

我是 JavaFX 新手,在单击按钮时仅更改场景的一个组件,而场景的其他组件保持不变,这让我很困难。 我有一个包含 2 个分区的 splitpane。一个部分包含一个带按钮的 HBox,另一部分包含一个 VBox。如何根据单击的按钮替换 VBox?预先感谢,下面是我的示例代码:

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);
    }

}

最佳答案

使用包装 Pane 来放置 vBox 怎么样?

Pane wrapperPane = new Pane();

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

然后:

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 );
);

等等...

关于javafx-8 - 如何在 JavaFX 中通过单击按钮替换场景组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30712396/

相关文章:

当节点没有父级时,JavaFX CSS 类不会被删除

java - 如何在 JavaFX 8 WebView 中设置/记住滚动条拇指位置?

java - 如何在 main 中使用我自己的类?

javafx 替换 BorderPane 的背景图像

JavaFx : Disable Divider

Javafx BorderPane 强制重叠

javafx-8 - JavaFx scenebuilder 和 Maven 集成

JavaFX 可调整 Canvas 大小的问题

Angular 2 Material Flex-layout 分割面板

css - 如何在 JavaFX 的 SplitPanes 上将分隔符位置绑定(bind)到像素而不是百分比?