Home > Software engineering >  java fx remove stackPane
java fx remove stackPane

Time:09-19

I need help creating a delete button on a stack pane in JavaFX. It should remove the chosen stack pane from the group. RinStackPane is extended javafx StackPane, gp is java fx Group. Thank you in advance! Here is my code:

private void setOnCreateMathOperation(Button createMathOperationBtn) {
    createMathOperationBtn.setOnAction(event -> {
        var mathOperation = createMathOperation();

        RinStackPane stack1 = new RinStackPane();
        stack1.setNodeType(NodesTypes.MathOperation);
        stack1.setUnderlyingNode(mathOperation);

        stack1.setName(mathOperation.getName());
        stack1.getChildren().add(mathOperation);

        TextField newtf1 = new TextField();
        GridPane grid = new GridPane();
        grid.addRow(1, newtf1);
        stack1.getChildren().add(grid);

        makeDraggable(stack1);
        addToRectCollection(stack1);

        gp.getChildren().add(stack1);
    });
}

CodePudding user response:

I am not sure if you want to keep the delete button inside or outside the StackPane.

Anyway you can easily bind an ObservableList to the Group's children. When an elemente will be deleted from the list, automatically this event will be reflected on Group's children:

//Create observable list of Node (you can constrain to RinStackPane if you prefer):
ObservableList<Node> list = FXCollections.observableArrayList();
//bind lists to gp's children:
Bindings.bindContentBidirectional(list, gp.getChildren());

Your code:

private void setOnCreateMathOperation(Button createMathOperationBtn) {
    createMathOperationBtn.setOnAction(event -> {

        RinStackPane stack1 = new RinStackPane();
        //...
        //setup the stack
        //...

        //Add the delete button to the stack:
        Button deleteButton = new Button("Delete me!");
        deleteButton.setOnMouseClicked(event -> {
            list.remove(stack1); //<--- remove action
        });
        stack1.getChildren().add(deleteButton);

        //add to the list instead of gp's children
        list.add(stack1);
    });
}

Note how the stack is not added nor removed to/from the gp's children, instead the list is used.

If you want the deleteButton outside the stack the code is the same, just be sure that both list and stack1 are somehow passed to the button's click handler.

Hope this helps.

  • Related