kneedhelp
kneedhelp

Reputation: 675

How to continuously scroll with JScrollPane

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?

Upvotes: 0

Views: 151

Answers (1)

camickr
camickr

Reputation: 324098

Check out the setAutoScrolls(...) method of the JComponent class.

You can just use:

panel.setAutoScrolls( true );

And then you use the following MouseMotionListener:

 MouseMotionListener doScrollRectToVisible = new MouseMotionAdapter() {
     public void mouseDragged(MouseEvent e) {
        Rectangle r = new Rectangle(e.getX(), e.getY(), 1, 1);
        ((JPanel)e.getSource()).scrollRectToVisible(r);
    }
 };
 panel.addMouseMotionListener(doScrollRectToVisible);

This concept is demonstrated in the ScollDemo example found in the Swing tutorial on How to Use Scroll Panes.

Upvotes: 2

Related Questions