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

社会主义新天地 提交于 2019-12-01 01:15:47

问题


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 the mouse pressed/released events for the back and forward mouse buttons. How can I handle this?

EDIT: This is using JDK 1.6.


回答1:


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



回答2:


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




回答3:


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);
}



回答4:


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) 


来源:https://stackoverflow.com/questions/7644842/how-can-i-use-the-back-and-forward-mouse-buttons-in-a-swing-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!