I want to override the mouse wheel listener in Swing but only if they have the Control button pressed. The listener will be attached to a JPanel so that when they scroll the wheel it will scroll the JScrollPane and when they have the control button pressed and scroll the wheel it will zoom in. The default scroll of JScrollPane works (obviously) before I override it with my own listener. Here is my code:
mainPanel.addMouseWheelListener(new MouseWheelListener(){
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
if ((e.getModifiers() & InputEvent.CTRL_MASK) == InputEvent.CTRL_MASK) {
int notches = e.getWheelRotation();
if (notches < 0) {
redrawOnZoom(true);
} else {
redrawOnZoom(false);
}
}
}
});
Is there a way of saying something like "If mouse is scrolled on its own then do default JScrollPane scrolling behaviour but If Ctrl is pressed then zoom"?
Usually it is not necessary to implement a mouse-wheel listener because the mouse wheel is used primarily for scrolling. Scroll panes automatically register mouse-wheel listeners that react to the mouse wheel appropriately.
Rotate the mouse wheel in the opposite direction. You will see mouse-wheel events in the down direction. Try changing your mouse wheel's scrolling behavior your system's mouse control panel to see how the output changes.
There is no way to programmatically detect whether the mouse is equipped with a mouse wheel. Alternatively, use the corresponding MouseAdapter AWT class, which implements the MouseWheelListener interface, to create a MouseWheelEvent and override the methods for the specific events.
If the mouse wheel rotated towards the user (down) the value is positive. If the mouse wheel rotated away from the user (up) the value is negative. Returns the number of units that should be scrolled per notch.
you can dispatch the event to its parent if you don't want to handle it:
final MouseWheelListener wheel = new MouseWheelListener() {
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
// handle some events here and dispatch others
if (shouldHandleHere(e)) {
LOG.info("do-my-own-stuff");
} else {
LOG.info("dispatch-to-parent");
e.getComponent().getParent().dispatchEvent(e);
}
}
public boolean shouldHandleHere(MouseWheelEvent e) {
return (e.getModifiersEx() & InputEvent.CTRL_DOWN_MASK) != 0;
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With