Loading images, audio, and other resources
suggest changeJava applets can load different resources. Because they run in the client’s web browser, those resources must be accessible to the applet. Applets cannot access client resources such as the local file system. To load a resource from the same URL where the applet is stored, use getCodeBase() to retrieve the base URL. To load resources, applets offer the methods getImage() and getAudioClip() to load images or audio files.
Load and show an image
public class MyImgApplet extends JApplet{
private Image img;
@Override
public void init(){
try {
img = getImage(new URL("http://cdn.sstatic.net/stackexchange/img/logos/so/so-logo.png"));
} catch (MalformedURLException e) { /* omitted for brevity */ }
}
@Override
public void paint(Graphics g) {
g.drawImage(img, 0, 0, this);
}
}
Load and play an audio file
public class MyAudioApplet extends JApplet{
private AudioClip audioClip;
@Override
public void init(){
try {
audioClip = getAudioClip(new URL("URL/TO/AN/AUDIO/FILE.WAV"));
} catch (MalformedURLException e) { /* omitted for brevity */ }
}
@Override
public void start() {
audioClip.play();
}
@Override
public void stop(){
audioClip.stop();
}
}
Load and display a text file
public class MyTextApplet extends JApplet{
@Override
public void init(){
JTextArea textArea = new JTextArea();
JScrollPane sp = new JScrollPane(textArea);
add(sp);
// load text
try {
URL url = new URL("http://www.textfiles.com/fun/quotes.txt");
InputStream in = url.openStream();
BufferedReader bf = new BufferedReader(new InputStreamReader(in));
String line = "";
while((line = bf.readLine()) != null) {
textArea.append(line + "\n");
}
} catch(Exception e) { /* omitted for brevity */ }
}
}
This snippet never closes in.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents