outellou outellou - 10 months ago 22
Java Question

How to catch a CTRL + mouseWheel event with InputMap

I've implemented some hotkeys for a Swing application with InputMap like

getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_A, Event.CTRL_MASK), "selectAll");
getActionMap().put("selectAll", new SelectAllAction());

it's working fine. Now, how can I do the same thing if I want to catch the

CTRL + MouseWheelUp

I've tried some combinations such as

getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(MouseEvent.MOUSE_WHEEL, Event.CTRL_MASK), "zoom");

with no luck



You can't use an InputMap/ActionMap for this. You need to use a MouseWheelListener. The listener can then access the custom Action from the ActionMap. Here is a simple example that uses "Control 1" for the KeyStroke:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MouseWheelTest extends JPanel implements MouseWheelListener {
    private final static String SOME_ACTION = "control 1";

    public MouseWheelTest() {
        super(new BorderLayout());

        JTextArea textArea = new JTextArea(10, 40);
        JScrollPane scrollPane = new JScrollPane(textArea);
        add(scrollPane, BorderLayout.CENTER);

        Action someAction = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("do some action");

        // Control A is used by a text area so try a different key

            .put(KeyStroke.getKeyStroke(SOME_ACTION), SOME_ACTION);
        textArea.getActionMap().put(SOME_ACTION, someAction);

    public void mouseWheelMoved(MouseWheelEvent e) {
        if (e.isControlDown()) {
            if (e.getWheelRotation() < 0) {
                JComponent component = (JComponent)e.getComponent();

                Action action = component.getActionMap().get(SOME_ACTION);

                if (action != null)
                    action.actionPerformed( null );
            } else {
                System.out.println("scrolled down");

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {

    private static void createAndShowGUI() {
        JFrame frame = new JFrame("MouseWheelTest");
        frame.add( new MouseWheelTest() );
        frame.setLocationRelativeTo( null );