How can I use the back and forward mouse buttons in a Swing application?

后端 未结 4 1405
南旧
南旧 2021-01-12 05:17

The question is pretty simple. I couldn\'t find many links regarding this issue, and the ones I found didn\'t seemed to avoid the real question. My application must handle t

相关标签:
4条回答
  • 2021-01-12 05:22

    Check if additional mouse buttons are detected by calling:

    MouseInfo.getNumberOfButtons();

    Check if MouseEvents are fired when you click those additional buttons. If so, what does MouseInfo.getButton() return?

    According to the javadocs for MouseInfo.getButton():

    If a mouse with five buttons is installed, this method may return the following values:

    * 0 (NOBUTTON)
    * 1 (BUTTON1)
    * 2 (BUTTON2)
    * 3 (BUTTON3)
    * 4
    * 5
    
    0 讨论(0)
  • 2021-01-12 05:22

    how can we distinguish between "back" and "forward" buttons? Can we be sure that button 4 is back and 5 is forward?

    I don't use JDK7 and have never heard of back/forward buttons. However I do know that the SwingUtilities class has methods:

    isRightMouseButton(MouseEvent)
    isLeftMouseButton(MouseEvent) 
    isMiddleMouseButton(MouseEvent) 
    

    If back/forward are now supported then I would guess they have added:

    isBackMouseButton(MouseEvent)
    isForwardMouseButton(MouseEvent) 
    
    0 讨论(0)
  • 2021-01-12 05:32

    Credit belongs to the original responders, just adding a ready-to-use code sample for global back-/forward-button detection in case it helps anyone else (JDK 1.8)

    if (Toolkit.getDefaultToolkit().areExtraMouseButtonsEnabled() && MouseInfo.getNumberOfButtons() > 3) {
        Toolkit.getDefaultToolkit().addAWTEventListener(event -> {
            if (event instanceof MouseEvent) {
                MouseEvent mouseEvent = (MouseEvent) event;
                if (mouseEvent.getID() == MouseEvent.MOUSE_RELEASED && mouseEvent.getButton() > 3) {
                    if (mouseEvent.getButton() == 4) {
                        // back
                    } else if (mouseEvent.getButton() == 5) {
                        // forward
                    }
                }
            }
        }, AWTEvent.MOUSE_EVENT_MASK);
    }
    
    0 讨论(0)
  • 2021-01-12 05:41

    Have a look at MouseEvent.getButton() and Toolkit.areExtraMouseButtonsEnabled().

    0 讨论(0)
提交回复
热议问题