Michelle Ler
Michelle Ler

Reputation: 55

JavaFx - How to get button array index if value is all the same

I have an issue when I tried to create multiple buttons with the same value of "x". How can I fix this issue or perhaps get the value of the buttons and then delete the specific element in an array with the same index as my button without deleting other elements as it loops through the for loop?

Button[] delButton = new Button[sizeOfIt]; //sizeOfIt is the size of array

for (int m=0; m <sizeOfIt; m++) {
    delButton[m]  = new Button("x");
}


for(int x = 0; x < delButton.length; x++) {                          
    delButton[x].setOnAction(new EventHandler<ActionEvent>() {     

        public void handle(ActionEvent event) {
        //  delete the element in the array with the same index as my button i clicked
        }
    });
}

Upvotes: 0

Views: 935

Answers (2)

SedJ601
SedJ601

Reputation: 13859

@azro example keeps up with the index to get a reference to the Buttons. This example uses actionEvent.getSource() to get a reference to the Buttons.

import java.util.Arrays;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Control;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Main extends Application
{
    int sizeOfIt = 10;

    @Override
    public void start(Stage primaryStage)
    {
        Button[] delButton = new Button[sizeOfIt]; //sizeOfIt is the size of array
        VBox vBox = new VBox();

        for (int m = 0; m < sizeOfIt; m++) {
            delButton[m] = new Button(m + "x");
            delButton[m].setOnAction(actionEvent -> {
                for (int i = 0; i < delButton.length; i++) {
                    if (delButton[i] != null && delButton[i].equals((Button) actionEvent.getSource())) {
                        vBox.getChildren().remove(delButton[i]);
                        delButton[i] = null;
                        System.out.println(Arrays.toString(delButton));
                    }
                }
            });
        }

        vBox.getChildren().addAll(delButton);
        vBox.setMaxSize(Control.USE_PREF_SIZE, Control.USE_PREF_SIZE);

        StackPane root = new StackPane(vBox);
        Scene scene = new Scene(root);
        primaryStage.setScene(scene);
        primaryStage.show();

    }

    public static void main(String[] args)
    {
        launch(args);
    }
}

Upvotes: 0

azro
azro

Reputation: 54148

You could handle this using the position of the button, it'll leave an empty box where the button was :

for(int x = 0; x < delButton.length; x++) {     
    final index = x;                     
    delButton[x].setOnAction(new EventHandler<ActionEvent>() {     
        public void handle(ActionEvent event) {
            delButton[index] = null;
        }
    });
}

Upvotes: 1

Related Questions