Rüschen의 Jannes :
나는 자바 (81 개) 2 차원 배열 버튼 객체를 가지고있다. (자바 FX) (9 개 버튼 각 HBox
)
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'
.
tgallei :
가장 좋은 방법은 확장하는 사용자 정의 버튼 클래스를 생성하는 것입니다 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;
}
}