Java AWT 鼠标事件

发布于 2024-12-21 15:09:36 字数 754 浏览 2 评论 0原文

我有一个使用 AWT 事件模型的小程序。它有一个布尔值,表示左按钮是否被按下。这是一个示例代码:

public class Game extends Applet implements MouseListener
{
    boolean isLeftButtonPressed;

    public void init()
    {
        addMouseListener(this);
        isLeftButtonPressed = false;
    }

    public void paint(Graphics g)
    {
        g.drawString("Is Button Pressed: " + isLeftButtonPressed, 20, 20);
    }

@Override
public void mouseClicked(MouseEvent e)
    {
        isLeftButtonPressed = true;
        repaint();
}

    @Override
public void mouseReleased(MouseEvent e)
    {
        isLeftButtonPressed = false;
        repaint();
}

    //Other MouseListener methods not listed but have to be implemented
}

但似乎左按钮永远不会释放,即使在您实际这样做之后也是如此。可能是什么问题?

I have an applet that makes use of the AWT event model. It has a boolean that says if the left button is pressed or not. Here is a sample code:

public class Game extends Applet implements MouseListener
{
    boolean isLeftButtonPressed;

    public void init()
    {
        addMouseListener(this);
        isLeftButtonPressed = false;
    }

    public void paint(Graphics g)
    {
        g.drawString("Is Button Pressed: " + isLeftButtonPressed, 20, 20);
    }

@Override
public void mouseClicked(MouseEvent e)
    {
        isLeftButtonPressed = true;
        repaint();
}

    @Override
public void mouseReleased(MouseEvent e)
    {
        isLeftButtonPressed = false;
        repaint();
}

    //Other MouseListener methods not listed but have to be implemented
}

But it seems as if the left button is never released, even after you actually do so. What could be the problem?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

2024-12-28 15:09:36

这其中的根本是不正确的,

这些是鼠标事件,

MousePressed ->    a mouse button is pressed
MouseReleased ->   a mouse button is released
MouseClicked ->   a mouse button is clicked (pressed and released)

因此,当您处理单击事件时,意味着鼠标被单击并释放。

所以我认为你必须使用鼠标按下而不是单击。

MouseEvent

The fundamental in this is incorrect,

These are the mouse events,

MousePressed ->    a mouse button is pressed
MouseReleased ->   a mouse button is released
MouseClicked ->   a mouse button is clicked (pressed and released)

So, when you handle the click event that means mouse is clicked and released.

So i think you have to use mousepressed instead of clicked.

MouseEvent

枯寂 2024-12-28 15:09:36

mouseClicked 方法将在 mouseReleased 方法之后调用,因此 isLgetButtonPressed 的值为 true。您必须使用 MouseEvent.getButton() 方法来检查按下了哪个鼠标按钮。

Method mouseClicked will be called after mouseReleased method so value of isLgetButtonPressed will be true. You have to use MouseEvent.getButton() method to check which mouse button is pressed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文