我有 81 个 Java 二维数组按钮对象。 (JavaFX)(每个 HBox
9 个按钮)
HBox[] hb = new HBox[9];
Button[][] btn = new Button[9][9];
// A for loop in another for loop to create 2d button arrays.
for (int i = 0; i < hb.length; i++) {
hb[i] = new HBox();
for (int j = 0; j < btn.length; j++) {
btn[i][j] = new Button();
btn[i][j].setText(Integer.toString(i) + "/" + Integer.toString(j));
btn[i][j].setOnAction(event -> {
System.out.println(event.getSource()); // In this line I want to print out the 2d array index values of a clicked button
});
hb[i].getChildren().add(btn[i][j]);
}
mvb.getChildren().add(hb[i]);
}
单击按钮时如何获取索引值?
例如,当我单击 btn[5][2]
时,我需要两个值 5 和 2,而不是 Button@277fbcb4[styleClass=button]'5/3'
.
最佳答案
最好的方法是创建一个自定义按钮类,该类扩展 Button
并包含这些值作为实例变量。
public void addButtons(Pane parentPane) {
HBox[] hb = new HBox[9];
Button[][] btn = new Button[9][9];
// A for loop in another for loop to create 2d button arrays.
for (int i = 0; i < hb.length; i++) {
hb[i] = new HBox();
for (int j = 0; j < btn.length; j++) {
btn[i][j] = new CustomButton(i, j);
hb[i].getChildren().add(btn[i][j]);
}
parentPane.getChildren().add(hb[i]);
}
}
class CustomButton extends Button {
private int i;
private int j;
public CustomButton(int i, int j) {
super();
this.i = i;
this.j = j;
setText(i + "/" + j);
setOnAction(event -> {
System.out.println(getI() + " " + getJ());
});
}
public int getI() {
return i;
}
public int getJ() {
return j;
}
}
关于java - 我需要在Java中获取二维数组对象的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60487764/