我的鼠标听筒好像不能用了。谁能帮帮我?我必须把一个球移动到我的鼠标点击的地方,但它不工作。

问题描述 投票:-3回答:1

这是代码,但它不工作。我以为我添加了正确的东西,但鼠标监听器甚至没有反应。需要很多帮助。

class Mouse implements MouseListener {
    /**
    * Moves the ball to the (x, y) location where the mouse has been clicked
    */
    public void mousePressed(MouseEvent e) {
        ball.setX(e.getX());
        ball.setY(e.getY());

        if (e.isMetaDown()) {
            ball.move(getX(), getY());
            repaint();
        }
        if (e.isShiftDown()) {
            ball.setRandomSpeed(20);
            ball.setLocation(Math.random(), Math.random());
            repaint();
        }
    }
}

如你所见,它没有工作。我不知道哪里出了问题。

java swing mouselistener
1个回答
-2
投票

你正在使用的是 java.awt.event.MouseEvent等。,对吗?

问题是,你调用的方法在 MouseEvent e 在你的情况下,不能像预期的那样工作。方法 e.isMetaDown()e.isShiftDown() 检查Meta修改器或Shift修改器在此事件中是否被关闭。我想你是在寻找一种方法来检查你是否按了左( MouseEvent.BUTTON1)或鼠标右键(MouseEvent.BUTTON3). 你可以参考这个页面。

https:/docs.oracle.comenjavajavase11docsapijava.desktopjavaawteventMouseEvent.html。

告知您的sef关于可以在以下情况下调用的方法。MouseEvents.

你可以试试这两个小改动。但是这段代码没有经过测试!)如果你希望有人来测试这段代码,那么请像@DontKnowMuchBut Getting Better已经提到的那样,发一个最小的可复制的例子。

class Mouse implements MouseListener {
    /**
    * Moves the ball to the (x, y) location where the mouse has been clicked
    */
    public void mousePressed(MouseEvent e) {
        ball.setX(e.getX());
        ball.setY(e.getY());

        if (e.getButton().equals(MouseEvent.BUTTON1)) {
            ball.move(getX(), getY());
            repaint();
        }
        if (e.getButton().equals(MouseEvent.BUTTON2)) {
            ball.setRandomSpeed(20);
            ball.setLocation(Math.random(), Math.random());
            repaint();
        }
    }
}

希望对大家有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.