FileDocCategorySizeDatePackage
ScrollableScribble.javaAPI DocExample2041Sat Jun 02 03:11:14 BST 2001None

ScrollableScribble.java

// This example is from the book _Java in a Nutshell_ by David Flanagan.
// Written by David Flanagan.  Copyright (c) 1996 O'Reilly & Associates.
// You may study, use, modify, and distribute this example for any purpose.
// This example is provided WITHOUT WARRANTY either expressed or implied.

import java.awt.*;

public class ScrollableScribble extends Panel {
    Canvas canvas;
    Scrollbar hbar, vbar;
    java.util.Vector lines = new java.util.Vector(100, 100);
    int last_x, last_y;
    int offset_x, offset_y;
    int canvas_width, canvas_height;
    
    // Create a canvas and two scrollbars and lay them out in the panel.
    // Use a BorderLayout to get the scrollbars flush against the 
    // right and bottom sides of the canvas.  When the panel grows,
    // the canvas and scrollbars will also grow appropriately.
    public ScrollableScribble() {
        // implicit super() call here creates the panel
        canvas = (Canvas) new BlankCanvas();
        hbar = new Scrollbar(Scrollbar.HORIZONTAL);
        vbar = new Scrollbar(Scrollbar.VERTICAL);
        this.setLayout(new BorderLayout(0, 0));
        this.add("Center", canvas);
        this.add("South", hbar);
        this.add("East", vbar);
    }
    
    // Draw the scribbles that we've saved in the Vector.
    // This method will only ever be invoked when the BlankCanvas
    // class (below) calls it.  It uses the Graphics object from the 
    // BlankCanvas object, and the Vector of lines from this class
    // to redraw everything.  
    // The offset_x and offset_y variables specify which portion of
    // the larger (1000x1000) scribble is to be displayed in the 
    // relatively small canvas.  Moving the scrollbars changes these
    // variables, and thus scrolls the picture.  Note that the Graphics
    // object automatically does clipping; we can't accidentally 
    // draw outside of the borders of the BlankCanvas.
    public void paint(Graphics g) {
        Line l;
        for(int i = 0; i