The Java URL Class
Home ] Up ]

 

 

Java's java.net.URL class encapsulates URLs. It has constructors:

URL(String absURL)
URL(URL baseURL, String relURL)
URL(String protocol, String host, String file)
URL(String protocol, String host, int port, String file)

Each of these constructors throws a MalformedURLException if the syntax for the resulting URL is incorrect. You must write code that is prepared for this exception:

try
{
    String url = "http://java.sun.com";
    URL u = new URL(url);
    // ...
}
catch (MalformedURLException e)
{
    // Deal with the exception...
}

getDocumentBase() and getCodeBase()

These methods of the javax.swing.JApplet (and java.applet.Applet) class return the following:

Method Description
getDocumentBase() returns the URL of the HTML file that contains the applet
getCodeBase() returns the URL of the applet

getImage() and getAudioClip()

These methods of the javax.swing.JApplet (and java.applet.Applet) class return the specified image and audio clip, respectively. 

For example:

package applets;

import java.applet.Applet;
import java.applet.AudioClip;

import java.awt.BorderLayout;
import java.awt.Color;

import java.net.MalformedURLException;
import java.net.URL;

import javax.swing.JApplet;
import javax.swing.JLabel;

import multimedia.ImagePanel;

public class MultimediaApplet extends JApplet
{
  public void init()
  {
    // First, create the image part of the GUI
    URL[] imageURLs = gatherImageURLs();
    getContentPane().add(new ImagePanel(imageURLs),
                         BorderLayout.CENTER);
    
    // Next, a label indicating the state of the audio part
    m_soundLabel = new JLabel("Loading audio clip...");
    m_soundLabel.setOpaque(true);
    m_soundLabel.setBackground(Color.WHITE);
    getContentPane().add(m_soundLabel, BorderLayout.SOUTH);
    
    // Load the audio clip
    loadAudioClip("audio/yahoo1.au");
    
    if (m_sound == null)
    {
      m_soundLabel.setText("No audio clip found...");
      m_soundLabel.setForeground(Color.RED);
    }
    else
    {
      m_soundLabel.setText("Playing audio clip...");
    }
  }
  
  public void start()
  {
    if (m_sound == null)
    {
      System.err.println("No audio clip to play!");
    }
    else
    {
      m_sound.play();
    }
  }
  
  private URL[] gatherImageURLs()
  {
    URL[] imageURLs = new URL[2];
    
    // Get the URL of applet
    URL baseURL = getCodeBase();
    System.out.println("CodeBase: " + baseURL);
    
    // Now get the URL for the first image file, below that directory
    URL imageURL = null;
    try
    {
      imageURL = new URL(baseURL, "images/bleye.gif");
      
      // Set in the first image URL.
      imageURLs[0] = imageURL;
      
      // The second image is on the web
      imageURLs[1] = new URL(
          "http://www.rivier.edu/faculty/bhiggs/web/cs585aweb/images/monalisa.jpg");
    }
    catch (MalformedURLException mue)
    {
      // Something wrong with our URL handling
      mue.printStackTrace();
    }
    
    return imageURLs;
  }
  
  private void loadAudioClip(String path)
  {
    AudioClip clip = null;
    URL baseURL = getCodeBase();
    System.out.println("Audio clip baseURL: " + baseURL);
    URL audioClipURL = null;
    try
    {
      audioClipURL = new URL(baseURL, path);
      System.out.println("Audio clip URL: " + audioClipURL);
      clip = Applet.newAudioClip(audioClipURL);
    }
    catch (MalformedURLException mue)
    {
      mue.printStackTrace();
    }
    m_sound = clip;
    System.out.println("Audio clip loaded.");
  }
  
  ///////// Data //////////////
  private JLabel m_soundLabel;
  private AudioClip m_sound = null;
}
package multimedia;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;

import java.net.URL;

import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class ImagePanel extends JPanel
{
  public ImagePanel(final URL[] imageURLs)
  {
    setBackground(Color.WHITE);
    setLayout(new BorderLayout());
    
    // Indicate that we're loading images,
    // which may take a long time.
    JLabel statusLabel = new JLabel("Loading Images...",
        JLabel.CENTER);
    statusLabel.setForeground(Color.BLACK);
    add(statusLabel, BorderLayout.CENTER);
    
    // Load the images in a separate thread to avoid
    // hanging up this thread waiting for load completion.
    Thread loader = new Thread()
    {
      public void run()
      {
        loadImages(imageURLs);
        // When done, cause a repaint from the 
        // event dispatcher thread
        SwingUtilities.invokeLater( new Runnable()
        {
          public void run()
          {
            // Remove the "Loading images..." label
            ImagePanel.this.removeAll();
            // and cause the images to display
            ImagePanel.this.repaint();
          }
        }
        );
      }
    };
    // Start the loader thread
    loader.start();
  }
  
  public void paintComponent(Graphics g)
  {
    super.paintComponent(g);
    
    if (m_imagesLoaded)
    {
      g.setColor(Color.BLACK);
      int x = 5;
      int y = 5;
      for (int i = 0; i < m_image.length; i++)
      {
        if (m_image[i] != null)
        {
          m_image[i].paintIcon(this, g, x, y);
          x += m_image[i].getImage().getWidth(this) + 5;
        }
        else
        {
          g.setColor(Color.RED);
          g.drawString("No image found", x, y);
        }
      }
    }
  }
  
  private void loadImages(URL[] imageURLs)
  {
    m_image = new ImageIcon[imageURLs.length];
    for (int i = 0; i < imageURLs.length; i++)
    {
      m_image[i] = new ImageIcon(imageURLs[i]);
    }
    m_imagesLoaded = true;
  }
  
  //// Private data /////
  private ImageIcon[] m_image;
  private boolean m_imagesLoaded;
}

Here's the result in a live applet:

Bad luck! Your browser is not Java enabled. You should be seeing an applet here...

If you don't see the applet, you probably need to install the Java Plug-in (JDK 1.4 or higher).

 

This page was last modified on 02 October, 2007