PaintDemo.java

Download PaintDemo.java

// This program shows how to display lightweight and heavyweight
// in a window with a "wallpaper" background.  By moving the
// super.paint(g) line to the top of the paint method, or by
// commenting it out completely, you can see that the heavyweight
// component is not affected.  But the lightweight one will
// appear behind the wallpaper, in front of the wallpaper, or
// not appear at all!
//
// Written 12/2008 by Wayne Pollock, Tampa Florida USA

import java.awt.*;
import java.awt.event.*;

class PaintDemo extends Frame
{
   public static void main ( String [] args )
   {
      Frame frame = new PaintDemo();
      frame.setVisible( true );
   }

   public PaintDemo ()
   {
      setSize( 300, 200 );
      setTitle( "Paint Demo" );
      setLayout( new FlowLayout(FlowLayout.CENTER, 20, 20) );

      Lightweight lightweight = new Lightweight();
      Heavyweight heavyweight = new Heavyweight();

      add( heavyweight );
      add( lightweight );

      addWindowListener( new WindowAdapter()
        {
          public void windowClosing ( WindowEvent e )
          {  dispose();  // Remove the last GUI component to exit.
          }
        }
      );
   }

   public void paint ( Graphics g )
   {
        // Paint horizontal stripes:
        Dimension size = getSize();
        Color colors[] = { Color.WHITE, Color.CYAN, Color.YELLOW };
        int thickness = 10;  // color strip height (in pixels)
        for ( int y = 0; y + thickness <= size.height; y += thickness )
        {
	   Color stripeColor = colors[ y % colors.length ];
	   // If the color is WHITE, don't draw it (transparent stripe)
           if ( stripeColor != Color.WHITE )
	   {
              g.setColor( stripeColor );
              g.fillRect( 0, y, size.width, thickness );
	   }
        }

        // Comment out the following and see what happens!
        super.paint( g );
   }
}

class Lightweight extends Component
{
    public Dimension getPreferredSize()
    {
        return new Dimension( 80,80 );
    }

   public void paint ( Graphics g )
   {
      g.setColor( Color.GREEN.brighter() );
      g.fillRect( 0, 0, getWidth(), getHeight() );
      g.setColor( Color.BLACK );
      g.drawString( "LightWeight", 5, 40 );
   }
}

class Heavyweight extends Canvas
{
    public Dimension getPreferredSize()
    {
        return new Dimension( 80,80 );
    }

   public void paint ( Graphics g )
   {
      g.setColor( Color.GREEN.brighter() );
      g.fillRect( 0, 0, getWidth(), getHeight() );
      g.setColor( Color.BLACK );
      g.drawString( "HeavyWeight", 3, 40 );
   }
}