Amine Harbaoui
Amine Harbaoui

Reputation: 1295

get event of a button that is dynamically added

I have this code that make user add files for attachment, and remove button to each file so my probleme is how can i get the event of the button when clicked

btnAttachment.setOnAction(event -> {
        FileChooser fileChooser = new FileChooser();
        selectedFiles.addAll(fileChooser.showOpenMultipleDialog(null));
        for (File selectedFile : selectedFiles) {
            HBox hBox = new HBox();
            hBox.getChildren().addAll(
                    new Label(selectedFile.getName() + " ( " + selectedFile.length() / 1024 + "Ko ) "),
                    new JFXButton("", new ImageView(new Image("/resources/images/minus-circle.png")))
            );
            vbAttachment.getChildren().add(hBox);
        }
        spAttachment.setVisible(true);
    });

and this image for more explanation

enter image description here

Upvotes: 0

Views: 114

Answers (1)

James_D
James_D

Reputation: 209724

Just add a listener to the button in the usual way. I have no idea what JFXButton is, so this is how you would do it using a regular JavaFX Button:

for (File selectedFile : selectedFiles) {
    HBox hBox = new HBox();

    Button removeButton = new Button("", new ImageView(new Image("/resources/images/minus-circle.png")));
    removeButton.setOnAction(evt -> {
        vbAttachment.getChildren().remove(hBox);
        // other code you need to execute when the button is pressed...
    });

    hBox.getChildren().addAll(
            new Label(selectedFile.getName() + " ( " + selectedFile.length() / 1024 + "Ko ) "),
            removeButton
    );
    vbAttachment.getChildren().add(hBox);
}

Upvotes: 1

Related Questions