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:
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?
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.