How to capture Ctrl mousewheel events using inputmap
•
Java
I have implemented some hotkeys for swing applications that use inputmap
getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(Keystroke.getKeystroke(KeyEvent.VK_A,Event.CTRL_MASK),"selectAll");
getActionMap().put("selectAll",new SelectAllAction());
It works normally Now, if I want to catch up, how can I do the same thing
I tried some combinations, such as
getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(Keystroke.getKeystroke(MouseEvent.MOUSE_WHEEL,"zoom");
No luck
thank you
Solution
You cannot use inputmap / actionmap You need to use mousewheel listener The listener can then access the custom action from the actionmap This is a simple example of keystroke using "control 1":
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);
}
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
