1

好的,所以我试图获取单击鼠标的正方形的网格上的坐标(为什么我将其转换为 int),这给了我鼠标的当前位置,但是,我想要单击后的位置和当它悬停时什么都不会发生。

我需要做什么?

while (gameOver==false){
    mouseX= (int) StdDraw.mouseX();
    mouseY=(int) StdDraw.mouseY();
    game.update(mouseX, mouseY);
}

我现在有

    public void mouseReleased(MouseEvent e){
       int mouseX = e.getX();
       int mouseY = e.getY();
               synchronized (mouseLock) {
    mousePressed = false;
}
}
public void run(){
    print();
    boolean gameOver=false;
    int mouseX,mouseY;
    StdDraw.setCanvasSize(500, 500);
    StdDraw.setXscale(0, game.gettheWidth());
    StdDraw.setYscale(0, game.gettheHeight());
    game.update(-1,-1);
    while (gameOver==false){

            mouseReleased(????)
            game.update(mouseX, mouseY);
        }       

}

还是行不通

这些都没有意义,

有人可以给我一个例子,说明它获取 x 和 y 坐标然后打印它们吗?我希望 mouseX 和 mouseY 成为 mouseclick 的坐标。我在网上看过我不明白其他任何问题,我认为它与mouseevent有关?

4

1 回答 1

0

StdDraw 实现了一个 MouseListener。重载 mouseReleased 方法来设置 mouseX 和 mouseY 变量。

要重载,请按照需要运行的方式重写方法:

int mouseX = 0;
int mouseY = 0;
public static void main(String[] args) {
    //do stuff
    //...
    while (gameOver == false) {
        //because mouseX and mouseY only change when the mouse button is released
        //they will remain the same until the user clicks and releases the mouse button
        game.update(mouseX, mouseY);
    }
}

//mouseReleased happens whenever the user lets go of the mouse button
@Override
public void mouseReleased(MouseEvent e) {
    //when the user lets go of the button, send the mouse coordinates to the variables.
    mouseX = e.getX();
    mouseY = e.getY();
    synchronized (mouseLock) {
        mousePressed = false;
    }
}

例如,mouseX 和 mouseY 都是 0。我在 处单击鼠标5, 6,拖动它,然后在 处释放鼠标120, 50。调用 mouseReleased 并将 mouseX 更改为 120,将 mouseY 更改为 50。同时,game.update(0,0) 一直在发生。现在变成了 game.update(120, 50),并且在我再次释放鼠标按钮之前将保持这种状态。

打印鼠标坐标:

@Override
public void mouseReleased(MouseEvent e) {
    //when the user lets go of the button, send the mouse coordinates to the variables.
    System.out.println("mouse x coord = " + e.getX());
    System.out.println("mouse y coord = " + e.getY());
    synchronized (mouseLock) {
        mousePressed = false;
    }
}
于 2014-05-05T02:20:40.820 回答