Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable zooming when using the mouse wheel (with a modifier ctrl or cmd) #18

Open
bric3 opened this issue Feb 7, 2022 · 0 comments
Open
Labels
enhancement New feature or request flamegraph

Comments

@bric3
Copy link
Owner

bric3 commented Feb 7, 2022

It seems that using InputMap / ActionMap may not the right approach instead a SO answer suggests to to use a proper listener.

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);
        textArea.addMouseWheelListener(this);

        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
        textArea.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
            .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() {
            @Override
            public void run() {
                createAndShowGUI();
            }
        });
    }

    private static void createAndShowGUI() {
        JFrame frame = new JFrame("MouseWheelTest");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add( new MouseWheelTest() );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible(true);
    }
}

https://stackoverflow.com/a/6702420/48136

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request flamegraph
Projects
None yet
Development

No branches or pull requests

1 participant