在 for 循环中侦听鼠标单击事件,并在后面的代码中使用该事件的坐标

Listen for a mouse click event inside a for loop and use the coordinates from that event in later code

我想做的是在我的其余代码中让它等待并识别鼠标单击事件,然后能够在其余代码中使用该单击的坐标,而不仅仅是将其打印到点击屏幕与我发现的几乎所有其他示例一样。

我是 java 的新手,这是我第一次制作界面,所以对于任何错误,我深表歉意,我会尽快修复它们。

不幸的是,因为我不知道如何做我要求的事情,所以我只能用一种伪代码和一些代码交叉来表示它,否则我不会一开始就在这里问地方。

编辑:下面的评论说不要这样做,我明白这一点,但我真的需要能够让那些坐标在代码的那个区域可用(比下面显示的要长很多)所以如果谁有其他方法可以实现,请分享。

在两个不同的位置单击两次以获得两个不同的坐标然后进行操作,这真的让我很困惑。

.....
for(int i = 0; i < 15; i++) {
    wait for mouse click;
    int x = x coordinate of mouse click;
    int y = y coordinate of mouse click;
    wait for mouse click;
    int x2 = x coordinate of second mouse click;
    int y2 = y coordinate of second mouse click;
    if (closestVertex(x,y) != closestVertex(x2,y2) && ! graph.isline(x,y,x2,y2)) {
        graph.insertLine(x,y,x2,y2);
    }
}
.... etc...

到目前为止,我看到的解决方案涉及查看指针在给定时刻的位置,但这不仅仅是在单击时的位置。此类解决方案如下所示:

int x = MouseInfo.getPointerInfo().getLocation.x;
int y = MouseInfo.getPointerInfo().getLocation.y;

另一种常见的做法是改变 MouseListener,如下所示:

@Override
public void mouseClicked(MouseEvent e) {
    int x=e.getX();
    int y=e.getY();
    System.out.println(x+","+y);
}

但是对于这个选项,是的,您可以打印坐标,但我没有看到可以在 mouseClicked 函数之外使用坐标详细信息的方法。

关于让它等待动作发生而不只是继续循环,我有几个想法。我想在内部添加一个 while 循环并使用 wait() 和 Thread.sleep(100) 但问题是我根本不知道如何说:

while(event hasn't occurred) {
    wait()
}
int x = x coordinate of mouse click;
int y = y coordinate of mouse click;
...etc

如果您有任何新想法我可以尝试,我将不胜感激,因为我已经经历过我什至不知道 google 上有多少链接正在寻找一种方法来完成这项工作。

您需要更改程序的控制流,以便您的代码响应 UI 事件,而不是尝试 运行 UI 本身。尝试这样的事情:

class MyStateMachine {
  int i = 0; // this is your loop index
  boolean waitingForSecondClick = false; // is the next click the first or second?
  int firstX; // coordinates of the first click
  int firstY;

  void receiveCoordinates(int x, int y) {
    if (waitingForSecondClick) { 
       if (closestvertex(....)) {
         // do your stuff
       }
       ++i;
       waitingForSecondClick = false;
    } else {
       firstX = x;
       firstY = y;
       waitingForSecondClick = true;
    }
  }

因此您的鼠标侦听器变为:

@Override
public void mouseClicked(MouseEvent e) {
    stateMachine.receiveCoordinates(e.getX(), e.getY())
}

您的对象第一次收到鼠标点击时,它只是将坐标保存在其实例变量中,并记住下一次点击是 'second click'。下一步单击它使用两次单击来完成您的任务,递增 i 并开始寻找另一个 'first click'.