Lukas Rotter
Lukas Rotter

Reputation: 4188

getImage()/drawImage() makes Java-Applet stop working

I'm making a 2D Java Game using JApplet. For the Graphics I obviously use Graphics respectively Graphics2D. My Problem: I want to display an image in my paintComponent(Graphics g) method. The picture is located in the same directory as the HTML5-File (in which the Applet is implemented) and the class files. Without the following code snippet, the applet works fine (except there's no image, obviously). But as soon as I add it to the class, the Applet doesn't start (in the Browser!). It won't display anything, and I don't get an exception.

Code:

Graphics2D gg = (Graphics2D) g;
Image img = getImage(getDocumentBase(), "img.PNG");
gg.drawImage(img, 70, 50, this);
gg.finalize();

Please note that I have Java Version 8 Update 51 installed and that I have the URL of the HTML5-File on my whitelist in the Java Control Panel (So I won't get a security-error). I tried the applet in Firefox and IE.

Upvotes: 2

Views: 76

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285430

  1. Never read in an image from within a painting method such as paint or paintComponent. Even if this were successful (it's not in your case), it will needlessly result in re-reading the image in multiple times and slowing down your program's perceived responsiveness -- the last thing that you want to do.
  2. Instead read the image in once and store it in a variable.
  3. Your problem has to be that you're not looking for the image in the right place -- with the right path. I recommend that you obtaine your Image as a resource from a URL or InputStream and use ImageIO.read(...) to read it in. You will need to find the correct path to the image, something hard for us to guess given your current question, but you will want to use a path relative to your class file locations.
  4. This, gg.finalize();, is dangerous code and should not be there; get rid of this line.

Upvotes: 2

Related Questions