16

在我的 javaFX 2.0 应用程序中,我需要替换一个使用 awt.CardLayout 的组件。Cardlayout 具有作为堆栈的功能,可显示堆栈中的顶部组件。我们也可以手动配置要显示的内容。

在 javaFX 2.0 中,有一个名为 StackPane 的布局。但它似乎不像 Cardlayout。

4

3 回答 3

13

另一种选择是使用 aStackPane并将除当前之外的所有可见性设置Panefalse。不是很理想,而是另一种思考问题的方式

于 2012-08-17T17:21:24.153 回答
13

没有 CardLayout,但您可以使用 TabPane 或简单地切换组:

public void start(Stage stage) {

    VBox vbox = new VBox(5);

    Button btn = new Button("1");
    Button btn2 = new Button("2");

    final Pane cardsPane = new StackPane();
    final Group card1 = new Group(new Text(25, 25, "Card 1"));
    final Group card2 = new Group(new Text(25, 25, "Card 2"));

    btn.setOnAction(new EventHandler<ActionEvent>() {
        public void handle(ActionEvent t) {
            cardsPane.getChildren().clear();
            cardsPane.getChildren().add(card1);
        }
    });

    btn2.setOnAction(new EventHandler<ActionEvent>() {
        public void handle(ActionEvent t) {
            cardsPane.getChildren().clear();
            cardsPane.getChildren().add(card2);
        }
    });

    vbox.getChildren().addAll(btn, btn2, cardsPane);
    stage.setScene(new Scene(vbox));
    stage.setWidth(200);
    stage.setHeight(200);
    stage.show();

}
于 2011-11-29T12:20:05.170 回答
2

使用 metasim 的答案,这里是完整的代码(也使按钮更像是切换按钮):

public void start(Stage stage)
{

    VBox vbox = new VBox(5);

    RadioButton btn = new RadioButton("1");
    RadioButton btn2 = new RadioButton("2");

    ToggleGroup group = new ToggleGroup();
    btn.setToggleGroup(group);
    btn2.setToggleGroup(group);

    btn.getStyleClass().remove("radio-button");
    btn.getStyleClass().add("toggle-button");        


    btn2.getStyleClass().remove("radio-button");
    btn2.getStyleClass().add("toggle-button");        

    final Pane cardsPane = new StackPane();
    final Group card1 = new Group(new Text(25, 25, "Card 1"));
    final Group card2 = new Group(new Text(25, 25, "Card 2"));

    cardsPane.getChildren().addAll(card1, card2);
    btn.setOnAction(new EventHandler<ActionEvent>()
    {
        public void handle(ActionEvent t)
        {
            showNodeHideNodes(cardsPane.getChildren(), card1);
        }
    });

    btn2.setOnAction(new EventHandler<ActionEvent>()
    {
        public void handle(ActionEvent t)
        {
            showNodeHideNodes(cardsPane.getChildren(), card2);
        }
    });

    vbox.getChildren().addAll(btn, btn2, cardsPane);
    stage.setScene(new Scene(vbox));
    stage.setWidth(200);
    stage.setHeight(200);
    stage.show();

}

private static void showNodeHideNodes(List<Node> nodes, Node nodeToShow)
{
    for (Node node : nodes)
    {
        if (node.equals(nodeToShow))
        {
            node.setVisible(true);
        } else
        {
            node.setVisible(false);
        }
    }

}
于 2018-10-09T14:06:33.327 回答