首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >获取鼠标在网格上单击的坐标easy java StdDraw

获取鼠标在网格上单击的坐标easy java StdDraw
EN

Stack Overflow用户
提问于 2014-05-05 10:09:56
回答 1查看 4K关注 0票数 1

好的,我正在尝试得到鼠标点击的方格上的坐标(为什么我将其转换为int),这给了我鼠标的当前位置,然而,我想要的是鼠标单击后的位置,并且在鼠标悬停时不会发生任何事情。

我该怎么办?

代码语言:javascript
复制
while (gameOver==false){
    mouseX= (int) StdDraw.mouseX();
    mouseY=(int) StdDraw.mouseY();
    game.update(mouseX, mouseY);
}

现在我有了

代码语言:javascript
复制
    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作为鼠标点击的坐标。我在网上看过了,其他问题我都不懂,我猜是和鼠标事件有关吧?

EN

回答 1

Stack Overflow用户

发布于 2014-05-05 10:20:41

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

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

代码语言:javascript
复制
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),并将一直保持到我再次释放鼠标按钮为止。

要打印鼠标坐标:

代码语言:javascript
复制
@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;
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23463793

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档