I'm using a JScrollPane to encompass a large JPanel. When the mouse is not within the bounds of the JScrollPane, I would like it to scroll in that direction. For example, if the top of the JScrollPane is at (100, 100) and the mouse is above the top of the component, I would like it to scroll upwards.
So far I found this:
private Point origin;
in the constructor...
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
origin = new Point(e.getPoint());
}
});
addMouseMotionListener(new MouseAdapter() {
public void mouseDragged(MouseEvent e) {
if (origin != null) {
JViewport viewPort = (JViewport) SwingUtilities.getAncestorOfClass(JViewport.class, Assets.adder.viewer);
if (viewPort != null) {
Rectangle view = viewPort.getViewRect();
if (e.getX() < view.x) view.x -= 2;
if (e.getY() < view.y) view.y -= 2;
if (view.x < 0) view.x = 0;
if (view.y < 0) view.y = 0;
if (e.getX() > view.x + view.getWidth()) view.x += 2;
if (e.getY() > view.y + view.getHeight()) view.y += 2;
scrollRectToVisible(view);
}
}
}
});
This works, but it only works when the mouse is in motion, otherwise it does not. How can I make it work while the mouse is outside of the JScrollPane, but also not moving?