Step 6

So that you may see the effects of moving the scrollbars, we add a very simple drawn object to the centerPanel object in the code, below. The approach is not a very good one for creating and displaying drawn objects, in general, but it serves our purpose here in an easy-to-understand manner. We will discuss a more efficient strategy for this process in a subsequent lesson concerning multimedia.

 


public class step4 extends Applet implements ActionListener, AdjustmentListener  {

// adds scrollbars and message display area

MyFrame outerBox;

Panel centerPanel;
Panel bottomPanel;

  public void init ( ){
    buildWindow ();
    drawSomething ();
  } // end init


  //****************** drawSomething

    // *** Global variables for drawing something

    int offsetX = 0;
    int offsetY = 0;
    int x = 300;
    int y = 250;

    private void drawSomething ()  {

        Graphics g = centerPanel.getGraphics ();
        Rectangle r = centerPanel.bounds ();
        g.setColor ( centerPanel.getBackground () );
        g.fillRect ( 0, 0, r.width, r.height );
        g.setColor ( new Color(170, 0, 0) );
        g.fillOval ( x + offsetX, y + offsetY, 200, 100 );

    }  // end drawSomething


  //****  AdjustmentListener method

  public void adjustmentValueChanged ( AdjustmentEvent e )  {

    Object s = e.getSource();


    // *** process Scrollbar actions

    if ( s instanceof Scrollbar )  {

        if ( s == scrollbarV )  {
            offsetY = - scrollbarV.getValue();
            drawSomething ();
        }

        if ( s == scrollbarH )  {
            offsetX = - scrollbarH.getValue();
            drawSomething ();
        }

    }  // end process scrollbar actions

  }  // end AdjustmentListener

We can now put all of the pieces together, which we do in the next step.