![]()
Displaying backgound Image in an Applet is a two step process.
First - Get the handle to the image using a simplified method getImage() or using the MediaTracker API. This is done in the Applet's init() method. Using the Media Tracker provides more events/notification that can handled ex.failed to load the media, etc.
Also with Media Tracker a variety of resource types can be retrieved not just image.
Finally - Once the image handle is there, draw the image at a given location in the Applet's paint(..) method with the drawImage(image,x,y, this) method.
The image can of any format like jpg, gif, png etc.
package com.livrona.snippets.applet;
import javax.swing.*;
import java.awt.*;
/**
* This snippet shows how to load background image in the Applet
* @author mvohra
*
*/
public class DisplayImageApplet extends JApplet {
private static final long serialVersionUID = -5674243667829955526L;
private Image im; // image handler
private static final String IMAGE = "background.gif";
/**
* Applet init() method
*/
public void init() {
// get the image
getImageSimple();
// or
// getImageWithMediaTracker();
}
/**
* Applet paint() method
*/
public void paint(Graphics g) {
// draw the image and location
int x = 0;
int y = 0;
// this is refers to image observer
g.drawImage(im, x, y, this);
}
/**
* Simply get the Image
*/
private void getImageSimple() {
// get the image
im = getImage(getDocumentBase(), IMAGE);
}
/**
* Get the Image and add Media Tracker to see image downloading
*/
private void getImageWithMediaTracker() {
// get image
im = getImage(getDocumentBase(), IMAGE);
// create and add Media Tracker
MediaTracker tracker = new MediaTracker(this);
// add the image to tracker and give it an id say 0
tracker.addImage(im, 0);
try {
// start loading the image with Id = 0
// in this case the image
tracker.waitForID(0);
} catch (InterruptedException e) {
System.out.println("Error loading Image : " + e.getMessage());
}
}
}
|
|
Related Links
- Display background Image in Applet
- How to playing an audio file in Applet?
- How to change Java Application Look and Feel?
- How to generate beep in Java?
- Find Files in Directory based on Extension
- Programmatically Toggle Function Keys
- How to redirect page to another url using Javascript?
- Apache DBCP BasicDatSource Setup
- How to Capture Screen Shot?
- Capture Screen shot as Image
- mvohra's blog
- Printer-friendly version
- Add new comment
- 2513 reads

- reply



Java Applet Recipes
Did you like this article? Did it Help you Solve your Problem? You can get the all the latest articles published at DeveloperFeed in your email inbox by entering your email address below. Your address will only be used for mailing you the articles, and each one will include a link so you can unsubscribe at any time.


Manpreet is an Architect & Software developer currently focusing on developing mobile apps on the iOS (iPhone/iPad) Platform. He’s the founder of a small iPhone development studio