Skip to main content

Set background Image to a JPanel

2 replies [Last post]
sy_cheung
Offline
Joined: 2003-06-10

Hi,

Can someone please tell me how can I put a background image to a JPanel?

I tried adding a JLabel to the panel (same size as the panel) and add other buttons on top of it. But that does not work.

Can someone else have other ideas?

Thank you.

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Scott Violet

On Mon, Mar 22, 2004 at 11:13:12AM -0500, swing-feedback@javadesktop.org wrote:
> Hi,
>
> Can someone please tell me how can I put a background image to a JPanel?
>
> I tried adding a JLabel to the panel (same size as the panel) and add other buttons on top of it. But that does not work.
>
> Can someone else have other ideas?
>
> Thank you.
> ---
> [Message sent by forum member 'sy_cheung' (sy_cheung)]
>
> http://www.javadesktop.org/forums/thread.jspa?messageID=8483&#8483

Making the JLabel the same size as the Panel should work. JLabel
won't scale the image though. Is it possible all the other widgets on
top of the JLabel are opaque so that you can't see through to the
JLabel with the image?

-Scott

shan-man
Offline
Joined: 2006-02-17

Hi,

> Hi,
>
> Can someone please tell me how can I put a background
> image to a JPanel?
>
> I tried adding a JLabel to the panel (same size as
> the panel) and add other buttons on top of it. But
> that does not work.
>
> Can someone else have other ideas?
>
> Thank you.

To display an image in the background of a JPanel, you'll need to paint it yourself. To do this, override [i]paintComponent[/i] to draw the image:
[code]
public ImagePanel extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, x, y, this);
}
}[/code]
See http://www.javadesktop.org/tsc/articles/swing2d/index.html for more information on custom painting.

Regards,
Shannon