javafx - 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.
}
}
解决方案
您应该能够调用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 命名约定并遵守它们。
推荐阅读
- ios - 创建构建文件时 Xcode 9.4 崩溃
- node.js - httpsProxyAgent 未定义
- c++ - modeltest + 简单表模式 = 父测试失败
- events - 生命周期事件 prePersist 是否与 Persist 以原子方式播放
- jquery - 如何防止 focusout 事件中的 mousedown 事件?
- swagger - 如何在 swagger 定义中提供字符串数组(默认值)
- python - 使用 SSL/TLS 将 Celery (Django) 连接到 RabbitMQ
- jquery - 如何在开发工具中隐藏这个内联 CSS
- r - 从 jsonlite 扩展通用方法 toJSON
- javascript - 防止用户离开输入字段