我有一个VBox的根节点。我还有一个使用窗格中的窗格和按钮创建的复合节点。复合节点的多个实例将添加到 VBox 中。我试图找到一种方法在触发每个复合节点的内部按钮时删除每个复合节点。但我没能找到办法。这是我的代码,有人可以帮我吗?
@Override
public void start(Stage primaryStage) {
VBox root = new VBox();
root.setAlignment(Pos.TOP_CENTER);
root.setSpacing(10);
Scene scene = new Scene(root, 300, 700);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
// 10 Non reffered instances will be added to the VBox(root)
for (int i=0; i<10; i++) {
Pane compositeChild = new Pane();
compositeChild.setPrefWidth(300);
compositeChild.setPrefHeight(40);
compositeChild.setBorder(new Border(new BorderStroke(Color.CORAL, BorderStrokeStyle.SOLID, CornerRadii.EMPTY, BorderWidths.DEFAULT)));
Button btn = new Button("Delete Me");
btn.setPrefWidth(200);
btn.setPrefHeight(30);
btn.setLayoutX(50);
btn.setLayoutY(5);
// I want to find some code for below action event
btn.setOnAction(e2 -> {
//how can I remove only one compositeChild that the event fired From the root(VBox)
((Button)e2.getSource()).setText("I should be deleted??");
});
compositeChild.getChildren().add(btn);
root.getChildren().add(compositeChild);
}
}
只是做
btn.setOnAction(e2 -> {
root.getChildren().remove(compositeChild);
});
你也可以这样做:
btn.setOnAction(e2 ->
{
if (btn.getParent() == null || btn.getParent().getParent() == null)
return;
((Pane)btn.getParent().getParent()).getChildren().remove(btn.getParent());
});