Lara
Lara

Reputation: 3

JavaFX: Getting IDs of Dynamic created Button

I'm currently made an Form with JavaFX. Always i press a Button, i call the "addAnswer()"-Method. In that I create a RadioButton, a Label and a delete-Button, which i bundle in a HBox. All that HBoxes i pack in a vBox. The Problem now is the delete-Button. I want to delte just THAT HBox in which the clicked Button is.

Here is my code:

public void addAnswer() {
    this.rB = new RadioButton();
    checkAnswer.getToggles().add(rB);
    hBox = new HBox();
    tF = new TextField();
    delAnswer = new Button("Löschen");
    delAnswer.setId(Integer.toString(counter));
    hBox.getChildren().addAll(rB, tF, delAnswer);
    hBox.setId(Integer.toString(counter));
    delAnswer.setOnAction(e -> delAnswer(Integer.parseInt(hBox.getId())));
    System.out.println(delAnswer.getId());

    vBox.getChildren().addAll(hBox);
    counter++;
}   

public void delAnswer(int e){  
    vBox.getChildren().remove(delAnswer.getId());

}

i tried this one above but i realized, that all the delAnswers-Buttons have the same ID: the number of how often i pressed the add-Button. Is there any solution where i can just select that one i pressed with that dynamic way? Cause i don't kow how often somebody will press or delete something.

Thanks

Upvotes: 0

Views: 1001

Answers (2)

fabian
fabian

Reputation: 82531

hbox is a field and this is why always the HBox last added is used. (hBox is evaluated, when lambda body is executed, not at the time of the lambda creation). This would be different, if you used a (effectively) final local variable:

final HBox hBoxLocal = hBox;
delAnswer.setOnAction(e -> delAnswer(Integer.parseInt(hBoxLocal.getId())));

However I'd like to present a different solution which would allow you to use the same EventHandler<ActionEvent> for all delete Buttons:

You can get the Node that triggered the event using getSource. From this Node you can get the parent, which is the HBox. You can remove this from the VBox using the remove(Object) method

delAnswer.setOnAction(e -> {
    // get button
    Node source = (Node) e.getSource();

    // remove parent of button from VBox
    vBox.getChildren().remove(source.getParent());
});

Upvotes: 1

Bo Halim
Bo Halim

Reputation: 1776

I think your problem is that you give the same event to all your button,Begin by creating a list that stores your buttons and then increments the value of the ID after affecting it to an item :

List<Button> buttons = new ArrayList<>();
/*
  Create Button and call IDEvt method to create new event
  for each button

*/
private void IDEvt(Button btn){

    btn.setId(String.valueOf(IDRank)); 

    btn.setOnMousePressed(new EventHandler<MouseEvent>() {

        @Override
        public void handle(MouseEvent event) {

            System.out.println(btn.getId());

        }
    });

    IDRank++;
 }

Upvotes: 0

Related Questions