Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

drawImage() in Java, why isn't the image loading ?  RSS feed

 
John McDowell
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have added the image in the src and bin directories and cross-checked that the name of the image file is correct

Here is the main class

import javax.swing.*;



and here is the class that does the image adding part


 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16007
87
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't use classes like ImageIcon very often, but I think the following is happening.

Look at the API documentation of the constructor of ImageIcon that you are using. It says:
Creates an ImageIcon from the specified file. The image will be preloaded by using MediaTracker to monitor the loading state of the image.

That means that the constructor will return before the image is actually loaded. The loading happens asynchronously, in a background thread. The class actually has a method named getImageLoadStatus to check whether the image is loaded or not.

First of all, you shouldn't load images in the paintComponent method. You don't want the program to load the image from disk every time the window is repainted. Do the loading somewhere else, in the initialization of the program.

Use some other mechanism to load the image. For example, ImageIcon has a loadImage method, that doesn't return until the image is loaded.
 
Campbell Ritchie
Sheriff
Posts: 55333
157
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
We usually discuss such questions in our GUIs forum. Moving.
 
Rob Camick
Ranch Hand
Posts: 2787
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Don't read the image in the paintComponent(...) method. Swing will invoke the painting method whenever it determines that the component needs to be repainted, so it doesn't make sense to continually read the image. Read the image when you create the class.

However, the real question is why are you creating a custom component for this? Just use a JLabel with an Icon. There is no need to reinvent the wheel.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!