disclaimer: This entry isn’t intended for a general audience. If you’re not a Swing programmer, you’ll probably want to skip it.

When the user flits about in a JScrollPane, the viewport’s view repeatedly repaints to maintain the illusion that the view component is sliding. This is usually a good thing, but sometimes the view is complicated and takes a long time to paint. This can freeze the GUI or chew up too many cycles.

In those situations one might prefer a ‘lazy’ scroll pane that doesn’t repaint the view while the user is dragging the thumb of the scroll bar, but does a single repaint when the user releases the thumb. Here’s an implementation:

import javax.swing.JViewport;
import javax.swing.JScrollPane;
import java.awt.Component;
import java.awt.Point;

 * a subclass of JViewport that overrides a method in order not
 * to repaint its component many times during a vertical drag
 * @author Brian Cole
public class LazyViewport extends JViewport {

     * equivalent to <b>new JScrollPane(view)</b> except uses a LazyViewport
    public static JScrollPane createLazyScrollPaneFor(Component view) {
        LazyViewport vp = new LazyViewport();
        JScrollPane scrollpane = new JScrollPane();
        return scrollpane;

     * overridden to not repaint during during a vertical drag
    public void setViewPosition(Point p) {
        Component parent = getParent();
        if ( parent instanceof JScrollPane &&
             ((JScrollPane)parent).getVerticalScrollBar().getValueIsAdjusting() ) {
            // value is adjusting, skip repaint

    private static final long serialVersionUID = 2006L;

This has been implentated to be lazy only when scrolling up and down, which is usually what I want. It would be simple to extend it to make horizontal scrolling lazy also.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s