2

Is it possible to have a HBox with a close button (i.e. a child button with the purpose of removing the HBox)? I am planning to implement it into something like this:

See image here.

I want to make a class of my own that inherits from the HBox class and has a close button already once it is instantiated. The close button needs to remove the HBox from the parent of the HBox (in this case, the VBox parent), not hide it. But I'm not sure if it is possible.

If it is possible, how should setOnAction of the close button be implemented?

fabian
  • 80,457
  • 12
  • 86
  • 114
muonsei
  • 23
  • 3
  • you could use hbox.getParent() to access the parent VBox and use vbox.getChildren().remove(hbox); to remove yourself – IEE1394 Nov 04 '17 at 09:54

1 Answers1

1

Sure this is possible:

EventHandler<ActionEvent> handler = event -> {
    // get button that triggered the action
    Node n = (Node) event.getSource();

    // get node to remove
    Node p = n.getParent();

    // remove p from parent's child list
    ((Pane) p.getParent()).getChildren().remove(p);
};
Button button = new Button("x");
button.setOnAction(handler);

Note that the same instance of the event handler can be reused for multiple close buttons, since you get the button that was clicked from the event object.

fabian
  • 80,457
  • 12
  • 86
  • 114