• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Putting an image in a JLabel

 
Kasun Liyanage
Greenhorn
Posts: 23
Java Netbeans IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi!

Ok, i have a JLabel on my app window, and i wanna load an image that resides on my harddisk or on the net into this already existing JLabel. i tried to do it like this from inside the main method by it gives me an error.


(jLabel1 label exists inside the NewJFrame frame)



How to fix this?
Thanks!
 
Paul Clapham
Sheriff
Posts: 21107
32
Eclipse IDE Firefox Browser MySQL Database
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Then that code must be in a static method of your class. We don't know what your class is called but let's suppose it's called "Test". Then do this:


Alternatively, restructure your code so that you aren't using a static method.
 
Kasun Liyanage
Greenhorn
Posts: 23
Java Netbeans IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks.

If i'm not using getResource(), what other ways are there to load an image (directly from harddisk/the net) to an already existing JLabel?



Appreciate if anyone could post some codes showing that.
 
Paul Clapham
Sheriff
Posts: 21107
32
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Any way which provides a URL which points to the image. If the image is on the net (and if it's accessible) then you'll have a URL pointing to it. If it's on the disk, then you can produce a File object which refers to it, and File has a method which produces a URL pointing to the file.

You would use the getResource() method if you knew the image was in your classpath somewhere (e.g. in a jar in the classpath).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic