ame
ame

Reputation: 347

How to load an image in Java using toolkit and new URL

I need to use a JPEG image in my Java applet. In my applet class, I define the image name and create an object to ImageBuffer class.

String iname= "image1.jpg";
b = new ImageBuffer(iname,this);

In the ImageBuffer class, I call

Image image = null;
image = Toolkit.getDefaultToolkit().getImage(new URL(applet.getCodeBase(),fileName));

While this does not flag an error and image is not null anymore, it does not initialize image correctly. The height and width are -1. The url of the path however appears to be correct : /C:/Users/..../image1.jpg

How do I correctly load the image? It is in the bin file of my Eclipse project currently.

Upvotes: 1

Views: 998

Answers (2)

Andrew Thompson
Andrew Thompson

Reputation: 168825

The height and width are -1.

Use a MediaTracker to monitor the asynchronous loading progress of the image. Alternately use ImageIO to load the image prior to the next code line.

Upvotes: 1

Extreme Coders
Extreme Coders

Reputation: 3511

If the image is placed in the correct location, then this would fix it

image = new ImageIcon(Toolkit.getDefaultToolkit().getImage(new URL(applet.getCodeBase(),fileName))).getImage();

If the code returns a NullPointerException it means the image is not placed in the correct directory.

Upvotes: 0

Related Questions