• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can i add an image directly to a JLabel or JWindow?

 
Robert Paris
Ranch Hand
Posts: 585
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How do I add an image to a JLabel or JWindow without needing to create a JLabel? Is there a way to do this?
 
Nathan Pruett
Bartender
Posts: 4121
IntelliJ IDE Java Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you are going to add it directly to a JLabel, why not just set the icon with an ImageIcon?

Otherwise, with any other JComponent, you can override paintComponent and with something like the following:


where the variable image is of class Image. image can be loaded in the constructor using Toolkit.getDefaultToolkit().getImage( filename ), or any other way you want.
 
Robert Paris
Ranch Hand
Posts: 585
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry. I'm an idiot, I meant JPanel.
As for overiding the paint() method, the problem is: what do I do about any other components they might add? Wouldn't it never paint them?
 
Ashish Hareet
Ranch Hand
Posts: 375
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's what I'd normally do -
I'd override the paintComponent(Graphics gX) & make the first line of that method call
super.paintComponent(g). That ways I'd be sure of the background work( if any ) being done. And the other thing is that the components you add to your subclassed panel will most likely overlap the custom painting you might have done.
HTH
Ashish Hareet
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic