java - 尝试创建一个方法,该方法采用鼠标单击的位置,并且应该返回一个作为所选单元格的单元格编号

标签 java function for-loop processing

我想创建并调用一个方法来检查网格上是否发生了点击。此方法应采用鼠标单击的位置,并应返回作为所选单元格的单元格编号。如果单击了一个单元格,则需要确定单击了哪个单元格并返回该单元格 数字。确保如果一个单元格已经被选中,而用户没有选择新的单元格,旧的 选定的单元格仍保持选中状态。如果用户单击一个单元格,并且该特定单元格 已经被选中,应该取消选中。在这种情况下,它应该返回 -1。 我这样做是为了获取单元格编号,但无法确保它保持选中状态并且无法返回 -1 以取消选择。

int cellSelected(int x, int y){
  int selected=-2;
  int left=40;

  for(int num=0; num<=12*8; num++)
  {
    int col = num%8;
    int row = num/8;
    left = 40+CELL_SIZE*col;
    int right = left+CELL_SIZE;
    int top = 40+CELL_SIZE*row;
    int bottom = top+CELL_SIZE;
    if (x >= left && x < right && y >= top && y < bottom)
    {
      selected = num;

    }
   }
  return selected;
}

最佳答案

要计算单元格的索引,只需将鼠标的相对位置(相对于网格的原点)除以单元格的大小即可。

int cellSelected(int x, int y){

     // position of the mouse relative to the grid
     int px = x - 40;
     int py = y - 40;

     // evaluate if the mouse is in the grid, return -1 else
     int cols = 8;
     int rows = 12;
     if (px < 0 || py < 0 || px > cols*CELL_SIZE || px > cols*CELL_SIZE) {
         return -1;
     }

     // calculate cell index (row and column of the cell)
     int col = px / CELL_SIZE;
     int row = py / CELL_SIZE;

     // return index of the cell
     return rows*cols + col;
}

关于java - 尝试创建一个方法,该方法采用鼠标单击的位置,并且应该返回一个作为所选单元格的单元格编号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58846732/

相关文章:

java.sequence处理运算符?

java - 对象的创建和委托(delegate)比一种大方法慢得多?

成员函数中的 C++ 线程

javascript - 从 JavaScript 中的嵌套函数返回

JavaScript 数组 - 迭代问题

java - 从 SurfaceView 和 Canvas 到 libGDX

java - 我尝试使用处理(Java)中的旋转和投影矩阵以 2D 形式渲染 3D 对象(立方体)

javascript - 分配给 {}.toString 是什么意思?

JavaScript——试图使用循环删除数组中的某些项目,但它删除了所有项目

swift - 在 for-in 循环中使用字符串宽度的问题