首页 > 解决方案 > JavaFX - 我如何知道 GridPane 中的按钮存在于何处?

问题描述

我有一个包含 GridPane 的 fxml 文件,我想在 GridPane 的每个正方形中找到按钮。然后我想在刚刚单击的按钮上显示图像。但是,当单击按钮并调用控制器中的方法时,似乎没有有关单击按钮位置的信息。没有这个,我不知道显示图像的正方形。我怎么解决这个问题?

我正在使用 JavaFX ScneBuilder2.0。我已经尝试过制作很多方法,其数量与 GridPane 中的正方形数量相对应。显然它导致生成太长的源文件,我放弃了这样做。

这是控制器类的一部分。

//GomokuController.java
package client;

import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;

public class GomokuController implements Initializable{
    @FXML private GridPane gomokuBoard;
    @FXML private Button[][] put_stone_button = new Button[15][15];

    @FXML public void put_stone(){
      //called by pushing a button in the GridPane
      //I wanna know in which square the pushed button locates.
    }
}

标签: javafxscenebuilder

解决方案


您应该能够调用GridPane.getRowIndex()andGridPane.getColumnIndex()方法并传入Button被点击的。

但是,您需要以某种方式将 传递Button给您的put_stone()方法。Button在下面的示例中,当单击按钮时,我将对您的方法的引用传递给该方法:

put_stone_button[0].setOnAction(event -> put_stone(put_stone_button[0])

public void put_stone(Button button){
  int row = GridPane.getRowIndex(button);
  int column = GridPane.getColumnIndex(button);
}

您可能需要将此解决方案调整到您的项目,因为您发布的代码中的实现不清楚。

旁注:请学习Java 命名约定并遵守它们。


推荐阅读