Вопрос

I'm trying to create a simple Java applet that can detect both the location of the mouse within the applet and detect whether the shift key has been released or pressed. When I add a KeyListener, though, the program ignores the mouseMove event. How can I get the mouseMove event to work while also using KeyListener?

public class Test extends java.applet.Applet implements java.awt.event.KeyListener {
    String message;
    int moveX, moveY;

    public Test() { this.addKeyListener(this); }

    public void init() {
        message = "";
        moveX = moveY = 0;
    }

    public void paint(java.awt.Graphics g) {
        new Test();
        g.drawString(message,15,15);
        g.drawString("(" + moveX + "," + moveY + ")",900,630);
    }

    @Override
    public void keyPressed(java.awt.event.KeyEvent e) {
        if (e.getKeyCode() == java.awt.event.KeyEvent.VK_SHIFT)
            message = "Shift key pressed";
        repaint();
    }

    @Override
    public void keyReleased(java.awt.event.KeyEvent e) {
        message = "Shift key released";
        repaint();
    }

    @Override
    public void keyTyped(java.awt.event.KeyEvent e) {}

    public boolean mouseMove(java.awt.Event e, int x, int y) {
        moveX = x;
        moveY = y;
        repaint();
        return true;
    }
}
Это было полезно?

Решение 2

I fixed the issue by replacing mouseMove(java.awt.Event e, int x, int y) with mouseMoved(java.awt.event.MouseEvent e), so now the coordinates change when the mouse's location changes and the message changes when the shift key is held down.

Другие советы

If you want to check if someone was holding shift or another key while clicking, MouseEvent has a method called getModifiers()

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top