Right.java - JApplet Image Loading Demo

Download this source file

Download Duke.gif image file

// An example of the right way to load an image from a JApplet, if the image
// might be in a JAR file.
//
// Points to note:  Swing GUI components should be created and manipulated from
// the AWT Event Handling Thread, not the Main Thread.  Since "init" is invoked
// from the Main Thread, the correct way to initialize the GUI is as shown,
// using a Runnable.  Also, pre-1.4 JREs had bugs in the Class.getResource
// method, so the Class.getResourceAsStream method must be used instead.
// Actually that method is slightly more efficient than getResource when you
// know the graphic is in a JAR, so it can be used instead.  It is not used
// here because it is an ugly method.
//
// For more information about JApplets and images, see:
// http://java.sun.com/docs/books/tutorial/uiswing/components/applet.html#images
//
// Written 2004 by Wayne Pollock, Tampa Florida USA.  All Rights Reserved.

import java.awt.*;
import java.net.*;
import javax.swing.*;

public class Right extends JApplet
{
   public void init ()
   {  try
      {  SwingUtilities.invokeAndWait( new Runnable()
            {  public void run () {  createGUI();  }
            }
         );
      }
      catch ( Exception ignored ) {}
   }

   public void createGUI ()
   {  URL imageURL = null;
      JLabel label = null;

      imageURL = getClass().getResource( "images/Duke.gif" );

      ImageIcon icon = new ImageIcon( imageURL );
      if ( icon.getImageLoadStatus() != MediaTracker.COMPLETE )
         label = new JLabel( "Can't load image!", JLabel.CENTER );
      else
         label = new JLabel( new ImageIcon( imageURL ) );

      getContentPane().add( label );
   }
}