Last Updated: February 3, 1997
The Problem
In the AWT1.0, the task of implementing all scrolling behavior is left to the developer. Only a basic Scrollbar class is provided which must be managed by the Java program, meaning the Java program must catch the scrollbar events and then take appropriate action to update the contents being scrolled.
Not only is this a general burden to developers who are accustomed to better support for this in toolkits, but it is also a serious performance problem, since there is a round trip (native->java->native) for each individual scroll event that occurs, and the application must respond to the event and move its contents using slower java draw/move operations. This is particularly noticeable during the event-intensive scroll-drag operations.
ScrollPane API
To resolve this problem, a ScrollPane class is being added to the AWT in 1.1. ScrollPane provides a container that implements automatic scrolling for a single component child:
The ScrollPane supports three modes for its scrollbars:
java.awt.ScrollPane
java.awt.Adjustable
Therefore, if a program wishes to set properties such as the unitIncrement,value, etc. on the scrollpane, it would first get the appropriate Adjustable and set the property there.
import java.awt.*;
public class Scroller extends Frame {
public Scroller() {
super("Scroller Example");
ScrollPane scroller = new ScrollPane(ScrollPane.SCROLLBARS_AS_NEEDED);
scroller.add(new DrawCanvas());
Adjustable vadjust = scroller.getVAdjustable();
Adjustable hadjust = scroller.getHAdjustable();
hadjust.setUnitIncrement(10);
vadjust.setUnitIncrement(10);
scroller.setSize(200, 200);
add("Center", scroller);
pack();
}
// No more handleEvent method needed to implement scrolling!
public static void main(String args[]) {
Scroller test = new Scroller();
test.show();
}
}
class DrawCanvas extends Component {
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
public void paint(Graphics g) {
// Note: For most efficient repainting, we should check the
// clip rectangle in the Graphics object to determine the
// damaged region and only paint that; we don't do that here
// for simplicity in this example
//
Rectangle r = getBounds();
g.setColor(Color.black);
g.fillRect(0, 0, r.width, r.height);
g.setColor(Color.yellow);
g.drawLine(0, 0, r.width, r.height);
g.setColor(Color.white);
g.drawLine(0, r.height, r.width, 0);
}
}