MouseWheelEvents
and the scrolling behavior have some subtle caveats.
For example, when you open this page (I mean THIS one, which you are currently reading), place the mouse in the middle, and start srolling down with the wheel, you will scroll over the code snippets. Note that although the code snippets are contained in code blocks that have a scrollbar, continuously rotating the mouse wheel will not trigger a scrolling in the code blocks, but only in the whole page. But when you once move the mouse while it is inside a code block, and afterwards roll the mouse wheel, then you will scroll in the code block only - and not the whole page.
Similarly, rotating the mouse wheel may not affect the hovered scrollable. I think it depends on the Window Manager and the Look & Feel, but in some cases, you will scroll the scroll pane that contains the focussed component - even if the mouse cursor is outside of this component, and even if it is over a scollable component (you can also observe this, for example, in the Windows Explorer)!
However, some of these mechanisms and subtleties can be found in the Swing components as well. For example, the redispatching mechanism that passes MouseWheelEvents
to the ancestors if they are not handled by the component itself.
Following this pattern, a solution (that is conceptually similar to the one that LuxxMiner proposed, but may be a tad more generic) may be to simply re-dispatch the MouseWheelEvent
to the parent component:
package stackoverflow;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
public class MouseWheelListenerForPanelInScrollpane
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
createAndShowGUI();
}
});
}
private static void createAndShowGUI()
{
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().setLayout(new GridLayout(1,2));
MouseWheelListenerPanel m = new MouseWheelListenerPanel();
m.setPreferredSize(new Dimension(100,4000));
JScrollPane scrollPane = new JScrollPane(m);
f.getContentPane().add(scrollPane);
f.setSize(500,500);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
class MouseWheelListenerPanel extends JPanel implements MouseWheelListener
{
MouseWheelListenerPanel()
{
addMouseWheelListener(this);
}
@Override
public void mouseWheelMoved(MouseWheelEvent e)
{
if (e.isControlDown())
{
if (e.getWheelRotation() < 0)
{
System.out.println("mouse wheel Up");
}
else
{
System.out.println("mouse wheel Down");
}
}
else
{
getParent().dispatchEvent(e);
}
}
}
MouseWheelListener
and the default scrolling of the page - How to stop the default scrolling while pressing [Ctrl] – Aylsworth