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

后端 未结 4 1397
南旧
南旧 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: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);
    }
    

提交回复
热议问题