我正在使用 javaFX 制作一个简单的国际象棋游戏。 我使用 fxml 文件创建棋盘,并使用 gridPane,每个单元格内都有一个按钮。 当用户按下按钮时,我想获取按下按钮的列和行索引。 有没有办法做到这一点? 我正在考虑使用这样的功能,但它不起作用。
private void buttonClicked(MouseEvent event) {
Button btn = (Button) event.getSource();
String nome = btn.getId();
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle(nome);
alert.setHeaderText(null);
alert.setContentText(nome);
alert.showAndWait();
}
我也做了同样的函数尝试打印父级的 id,但仍然不起作用。在 fxml 文件中,对该函数的调用如下:
<AnchorPane prefHeight="200.0" prefWidth="200.0" GridPane.columnIndex="1">
<children>
<Button layoutX="14.0" layoutY="19.0" mnemonicParsing="false" onAction="#buttonClicked" prefHeight="63.0" prefWidth="94.0" styleClass="blackButton" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
</children>
</AnchorPane>
最佳答案
您无法将参数传递给buttonclicked 处理程序。
但是您可以使用以下方式检索行/列坐标:
AnchorPane cellAnchorPane = (AnchorPane) btn.getParent();
int row = GridPane.getRowIndex(cellAnchorPane);
int col = GridPane.getColumnIndex(cellAnchorPane);
顺便说一句,我不知道您想要实现什么目标,但我认为按钮不需要位于 AnchorPane 内部。并且在fxml中创建chessBoard而不是代码会非常重复
看看这个示例应用程序。您可以创建一个处理程序并传递这些参数
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
GridPane gridpane = new GridPane();
Scene scene = new Scene(gridpane, 400, 400);
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
Button b = new Button("cell " + i + " - " + j);
final int col = i;
final int row = j;
b.setOnAction(a -> buttonClicked(col, row));
gridpane.add(new AnchorPane(b), i, j);
}
}
primaryStage.setScene(scene);
primaryStage.show();
}
private void buttonClicked(int col, int row) {
System.out.println("button : " + col + " -" + row + " pressed");
}
public static void main(String[] args) {
launch(args);
}
}
关于JAVAFX:带参数的OnAction事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51880919/