Insert Images and Audio in Java Applet

Displaying Images
An applet can display images of the format GIF, JPEG, BMP, and others. To display an image within the applet, you use the drawImage() method found in the java.awt.Graphics class.
Example: - To Display image in Applet
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Image;
public class DisplayImageExample extends Applet
{
Image img1, img2;
public void init(){
img1 = getImage(getDocumentBase(), getParameter("Image1"));
img2 = getImage(getDocumentBase(), getParameter("Image2"));
}
public void paint(Graphics g){
//display an image using drwaImage method of Graphics class.
g.drawImage(img1, 0,0,this);
g.drawImage(img2, 100,100,this);
}
}
/*
< applet code = "DisplayImageExample.class" width = 500 height = 300 >
< param name = "Image1" value = "images/jc21.jpg" >
< param name = "Image2" value = "images/jc19.jpeg" >
< /applet >
*/
Output: -
C:\java\applet>javacDisplayImageExample.java
C:\java\applet>appletviewer DisplayImageExample.java

Play Audio
Example: - To play Audio in wav format..
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class PlaySoundApplet extends Applet implements ActionListener{
Button play,stop;
AudioClip audioClip;
public void init(){
play = new Button(" Play in Loop ");
add(play);
play.addActionListener(this);
stop = new Button(" Stop ");
add(stop);
stop.addActionListener(this);
audioClip = getAudioClip(getCodeBase(), "image.wav");
}
public void actionPerformed(ActionEvent ae){
Button source = (Button)ae.getSource();
if (source.getLabel() == " Play in Loop "){
audioClip.play();
}
else if(source.getLabel() == " Stop "){
audioClip.stop();
}
}
}
/*
< HTML >
< BODY >
< APPLET CODE="PlaySoundApplet.class" WIDTH="200" HEIGHT="300" >
< /BODY >
< /HTML >
*/
Output: -
C:\applet>javac PlaySoundApplet.java
C:\applet>appletviewer PlaySoundApplet.java


Free Web Hosting