I am developing a desktop application in netbeans in which I have an editor class that's a sub-class of a class that has a JScrollPane
. (JScrollPane
has two JScrollBars
: horizontal & vertical.) Everything works as expected including being able to scroll with the mouse wheel both vertically (no modifiers) and horizontally (by using the shift modifier).
Another super class (between my class and the JScrollPane
class) implements zooming (which works fine (including scrolling) by setting my zoom (scale) factor via menu commands).
What I want is to be able to zoom in/out via the mouse wheel when the alt (option) key is down (isAltDown()
is true) and fallback to the default scroll (H&V) behavior otherwise. Here's part of my class setup code:
JScrollPane scrollPane = getPanelScrollPane();
JScrollBar hsb = scrollPane.getHorizontalScrollBar();
JScrollBar vsb = scrollPane.getVerticalScrollBar();
MouseWheelListener mwl = new MouseWheelListener() {
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
if (e.isAltDown()) {
double oldZoom = getZoom();
double amount = Math.pow(1.1, e.getScrollAmount());
if (e.getWheelRotation() > 0) {
//zoom in (amount)
setZoom(oldZoom * amount);
} else {
//zoom out (amount)
setZoom(oldZoom / amount);
}
} else {
// pass the event on to the scroll pane
getParent().dispatchEvent(e);
}
}
};
// add mouse-wheel support
hsb.addMouseWheelListener(mwl);
vsb.addMouseWheelListener(mwl);
This setup code is getting called but the mouseWheelMoved
method is never called when I move the mouse wheel (while the cursor is over my view); The view continues to scroll (H&V) normally.
I've also tried adding "implements MouseWheelListener
" and a mouseWheelMoved
method to my class:
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
// (same as mouseWheelMoved above)
}
Still no luck… What am I missing? (Edit: Bonus questions about propagating wheel events removed: answered here: <How to implement MouseWheelListener for JPanel without breaking its default implementation?>).