How to catch CTRL + mouseWheel event using InputMap

I have implemented some hotkeys for a Swing application with InputMap, for example

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

It works fine. Now how can I do the same if I want to catch

CTRL + MouseWheelUp

I tried some combinations like

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

bad luck

thanks

+6
source share
3 answers

You cannot use InputMap / ActionMap for this. You need to use MouseWheelListener. The listener can then access the custom Action from the ActionMap. Here is a simple example that uses "Control 1" for 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); 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); } } 
+6
source

In my case, I want to listen to JPanel , so it was easy to use MouseWheelListener .

Here is my code:

 @Override public void mouseWheelMoved(MouseWheelEvent e) { if (e.isControlDown()) { if (e.getWheelRotation() < 0) { System.out.println("Zoom-in when scrolling up"); } else { System.out.println("Zoom-out when scrolling down"); } } } 

thanks

+1
source

Try typing InputEvent.CTRL_DOWN_MASK instead of Event.CTRL_MASK. According to JavaDoc: "It is recommended to use CTRL_DOWN_MASK."

0
source

Source: https://habr.com/ru/post/892794/


All Articles