Download this source file
/*
*/
// HeavyLight Applet showing the difference between heavyweight and
// lightweight components.
// Adopted from "Graphic Java 1.2: Mastering the JFC", 3rd Edition,
// Volume 1, (C) 1999 by Sun Microsystems, Inc. Published by Prentice-Hall.
// Written by Wayne Pollock, Tampa Florida USA, March 2000.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class HeavyLight extends Applet
{
private Image dining, paper;
public void init ()
{
showStatus( "Loading Media..." ); // Display msg in status bar.
dining = getImage( getCodeBase(), "Dining.gif" );
paper = getImage( getCodeBase(), "paper.gif" );
MediaTracker mt = new MediaTracker( this );
try
{
mt.addImage( dining, 0 );
mt.addImage( paper, 1 );
mt.waitForAll();
}
catch( InterruptedException e ) { e.printStackTrace(); }
if ( mt.isErrorAny() )
dining = paper = null;
add( new Heavyweight( dining ) );
add( new Lightweight( dining ) );
setBackground( Color.white );
setVisible( true );
}
public void paint ( Graphics g )
{
if ( paper == null )
{
g.drawString( "Error loading images!", 30, 45 );
return;
}
wallPaper( g, paper ); // paint the background first...
super.paint( g ); // ...before painting components!
}
public void wallPaper ( Graphics g, Image image )
{
Dimension myArea = getSize();
int tileWidth = image.getWidth( this );
int tileHeight = image.getHeight( this );
for ( int row = 0; row < myArea.width; row += tileWidth )
for ( int col = 0; col < myArea.height; col += tileHeight )
g.drawImage( image, row, col, this );
}
}
class Lightweight extends Component // A Component has no peer, so is lightweight
{
private Image image;
private Dimension mySize;
public Lightweight ( Image im )
{
image = im;
mySize = new Dimension( image.getWidth( this ), image.getHeight( this ) );
}
public void paint ( Graphics g ) { g.drawImage( image, 0, 0, this ); }
public Dimension getPreferredSize () { return mySize; }
}
class Heavyweight extends Panel // A Panel has a peer, so is heavyweight.
{
private Image image;
private Dimension mySize;
public Heavyweight ( Image im )
{
image = im;
mySize = new Dimension( image.getWidth( this ), image.getHeight( this ) );
}
public void paint ( Graphics g ) { g.drawImage( image, 0, 0, this ); }
public Dimension getPreferredSize () { return mySize; }
}