简体   繁体   中英

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 );
}

}

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:

在此处输入图片说明

getDocumentBase( )

Java will allow the applet to load data from the directory holding the HTML file that started the applet (the document base) This document base URL object is returned by the function getDocumentBase( )

getCodeBase( )

The directory from which the applet's class file was loaded(the code base) This code base URL object is returned by the function getCodeBase( ).

Example code:

示例代码

Example output:

输出值

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM