LazyViewport
Posted by bitguru on January 7, 2008
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();
vp.setView(view);
JScrollPane scrollpane = new JScrollPane();
scrollpane.setViewport(vp);
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
return;
}
super.setViewPosition(p);
}
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.