简体   繁体   中英

How to react on special mouse keys in Java (forward/backward keys)

I´m using KeyBindings and MouseListener to react on keyboard/mouse inputs. Many mouses have a back/forward button (for example to go a page back and forth in a webbrowser). How can I react on these buttons in Java?

Special mouse keys are usually bound by the mouse's vendor software to virtual keystrokes. Try implementing a KeyListener , set a breakpoint inside the keyPressed method, debug and watch which keyCode do you get when you press a special button on your mouse. This way, you would likely also handle special keys on keyboards which often also provide the same functionality.

Just implement a MouseListener and have a look at the mousePressed() event.

Quick and dirty program to test mouse buttons:

package stackoverflowanswer;

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class MouseListenerApp{
public static void main(String[] args) {        
    Runnable r = new Runnable(){
        @Override
        public void run() {
            JFrame frame = new JFrame("mouselistener"); 
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            frame.addMouseListener(new MouseListener() {
                @Override
                public void mouseClicked(MouseEvent e) {
                }

                @Override
                public void mousePressed(MouseEvent e) {
                    System.out.println(e.getButton());
                }

                @Override
                public void mouseReleased(MouseEvent e) {
                }

                @Override
                public void mouseEntered(MouseEvent e) {
                }

                @Override
                public void mouseExited(MouseEvent e) {
                }
            });

            frame.setSize(200,200);
            frame.setVisible(true);
        }
    };

    SwingUtilities.invokeLater(r);
    }
}

For me forward/backward corresponds to key 4/5.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM