javaswingmouse-listeners

Custom wheel listener prevent ScrollPane Wheel Listener


I add a custom mousewheellistener to my JPanel, because I will implement zoom feature for this panel which working with ctrl+mousewheel. Also my JPanel is in a JScrollpane. My problem is; when I adding MouseWheelListener to the panel, mouse wheel doesn't work for scrollpane even if Ctrl is not pressed. I want that; mouse wheel work for zoom when ctrl pressed and if not pressed it should work for scrollpane. How can I do that?

public class ZoomTest {

    public static void main(String[] args) {
        JPanel jZoomPanel = new JPanel();
        jZoomPanel.setPreferredSize(new Dimension(300, 500));
        jZoomPanel.addMouseWheelListener(new MouseWheelListener() {

            @Override
            public void mouseWheelMoved(MouseWheelEvent e) {
                if(e.isControlDown()) {
                // TODO implement zoom
                }
            }
        });

        JScrollPane jsc = new JScrollPane(jZoomPanel);

        JFrame jDemoFrame = new JFrame();
        jDemoFrame.getContentPane().add(jsc);
        jDemoFrame.setSize(300, 300);

        jDemoFrame.setVisible(true);
    }

}

Solution

  • You should dispatch your event like this:

    jZoomPanel.addMouseWheelListener(new MouseWheelListener() {
    
        @Override
        public void mouseWheelMoved(MouseWheelEvent e) {
            if(e.isControlDown()) {
            // TODO implement zoom
            } else {
                JPanel panel = (JPanel) me.getSource();
                MouseEvent newMe = SwingUtilities.convertMouseEvent(panel, me, jsc);
                jsc.dispatchEvent(me);
            }
        }
    });