permaculture playing cards*
The moose likes Swing / AWT / SWT and the fly likes Can i add an image directly to a JLabel or JWindow? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Can i add an image directly to a JLabel or JWindow?" Watch "Can i add an image directly to a JLabel or JWindow?" New topic
Author

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

Robert Paris
Ranch Hand

Joined: Jul 28, 2002
Posts: 585
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

Joined: Oct 18, 2000
Posts: 4121

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.


-Nate
Write once, run anywhere, because there's nowhere to hide! - /. A.C.
Robert Paris
Ranch Hand

Joined: Jul 28, 2002
Posts: 585
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

Joined: Jul 14, 2001
Posts: 375
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
 
jQuery in Action, 2nd edition
 
subject: Can i add an image directly to a JLabel or JWindow?