如何在我的Javafx 2.0应用程序中实现AWT.CardLayout的功能?
-
25-10-2019 - |
题
在我的Javafx 2.0应用程序中,我需要替换一个使用Awt.Cardlayout的组件。 CardLayout具有堆栈功能,可在堆栈中显示顶部组件。而且,我们也可以手动配置要显示。
在Javafx 2.0中,有一个名为Stackpane的布局。但这似乎并不像纸牌。
解决方案
没有纸牌套,但是您可以使用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();
}
其他提示
另一个选择是使用 StackPane
并设置除疗养者以外的所有人的可见性 Pane
至 false
. 。不是理想的,但是另一种思考问题的方式
使用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);
}
}
}
不隶属于 StackOverflow