JavaFx-如果值都相同,如何获取按钮数组索引

时间:2018-11-08 18:43:15

标签: java javafx

当我尝试创建多个具有相同“ x”值的按钮时出现问题。我该如何解决此问题,或者获取按钮的值,然后删除与按钮具有相同索引的数组中的特定元素,而不删除其他元素,因为它在for循环中循环?

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
        }
    });
}

2 个答案:

答案 0 :(得分:1)

您可以使用按钮的位置进行处理,它将在按钮所在的位置留下一个空框:

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;
        }
    });
}

答案 1 :(得分:0)

@azro示例跟踪索引以获取对Buttons的引用。本示例使用actionEvent.getSource()获取对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);
    }
}