user3666515 user3666515 - 3 months ago 16
Java Question

How do you use getDocumentBase() and getCodeBase() correctly in Java Applets?

I am working on a project, and I'm new to applets. I don't know how to find a file using these arguments. I know there is another question out there that is almost the same, but I want this in an easy, simplified way because I'm new to this. Any help would be awesome!!! Here is my code:

import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.Graphics;

public class SoundDemo extends Applet
{
public void init()
{
AudioClip clip = getAudioClip( getCodeBase(), "sounds/Dragon Roost.wav" );
clip.play();
}

public void paint( Graphics g )
{
g.drawString( "Now Playing Clip", 10, 10 );
}


}

Answer

It might help you to understand. Here I am reading a music file that is stored under music folder in src folder of my project as shown in below snapshot.

getDocumentBase() points to the bin folder (class-path) where all the classes are stored.

In your case it will fetch the music from bin/sounds/Dragon Roost.wav


getDocumentBase()

Gets the URL of the document in which this applet is embedded. For example, suppose an applet is contained within the document:

http://java.sun.com/products/jdk/1.2/index.html

The document base is:

http://java.sun.com/products/jdk/1.2/index.html

getCodeBase()

Gets the base URL. This is the URL of the directory which contains this applet.


Sample code:

Applet:

URL url = getDocumentBase();
AudioClip audioClip = getAudioClip(url, "music/JButton.wav");

Project structure:

enter image description here

Comments