Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Are all Middle Clicks in Java Reported as Having the Alt Modifier?

Why do the MouseEvents in Java share modifiers between keys and mouse buttons?

Consider, the simple code below:

public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setSize(800,600);
    frame.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
            System.out.println(e);
        }
    });
    frame.setVisible(true);
}

If you click three times in the window (one left click, one middle click, and one right click) you'll see the following output.

java.awt.event.MouseEvent[MOUSE_CLICKED,(165,149),absolute(165,149),button=1,modifiers=Button1,clickCount=1] on frame0
java.awt.event.MouseEvent[MOUSE_CLICKED,(292,228),absolute(292,228),button=2,modifiers=Alt+Button2,clickCount=1] on frame0
java.awt.event.MouseEvent[MOUSE_CLICKED,(293,228),absolute(293,228),button=3,modifiers=Meta+Button3,clickCount=1] on frame0

If you look, you'll notice that all middle clicks are reported as having the alt key down, and all right clicks are reported as having the Meta key down. This is well documented, and there is even a line in the Javadocs for MouseEvent mentioning this overlap. But my question is, why is it reported like this? What is the reasoning behind returning true from e.isAltDown() for a middle click?

This makes it difficult to distinguish between Alt+Button1 and Button2 on some platforms.

Similarly, are there any "Best Practices" guides for designing cross-platform mouse behaviors in Java?

like image 722
JohnnyO Avatar asked Mar 06 '13 18:03

JohnnyO


1 Answers

I believe this re-use of flags is for historic reasons. I can only guess about the original motivations, but one might have been not using too many bits so that more bits remain available for future extensions. Another might have been the fact that Mac only had a single mouse, so modifiers were (and still are) commonly used on Mac to denote things for which one would usually use a different mouse button on systems with a sufficient number of these.

Since Java 1.4 I'd rather use getModifiersEx which will report these modifiers and the buttons separately. So the information is available, it just isn't reported through the old interface in order to maintain backwards compatibility.

like image 59
MvG Avatar answered Sep 23 '22 06:09

MvG