How to set the background of a JPanel as an image

Hi everyone,

Could anyone help me on how to set up an image background in JPanel? For example, in a chess game, I want to have an image board instead of having cells with color. What I did was

First I overriddent the paint method in JPanel ie:

public void paint(Graphics g) {

super.paint(g);

g.drawImage(backgroundImage, 0, 0, sizeX, sizeY, this)

}

Then , I added pieces (also JPanels which images) on this panel...When I run it, the pieces were drawed first, then the backgoundImage appeared and overlapped it. All I could see on the Panel was just the backgoundImage....I must be doing something wrong here..

Any help would be appreciated.

Thank you,

Tam

[723 byte] By [nhantamda] at [2007-9-27 5:59:32]
# 1
Check http://forum.java.sun.com/thread.jsp?forum=57&thread=126730Patrick
lachpa at 2007-7-8 8:26:43 > top of Java-index,Archived Forums,Swing...
# 2
Thanks but the link which your link takes to does not work...maybe this question was asked too long ago...
nhantamda at 2007-7-8 8:26:43 > top of Java-index,Archived Forums,Swing...
# 3

First of all, you should override paintComponent() not paint(). This section from the Swing tutorial on "Painting" will explain why:

http://java.sun.com/docs/books/tutorial/uiswing/overview/draw.html

Don't forget to click on the "Working with Graphics" link at the bottom.

Take a look at the order of your two statements:

1) paint the panel (and its components)

2) draw image overtop

Try reversing the order.

Here is a thread that show how to add an image to a JTextArea. The principle is the same:

http://forum.java.sun.com/thread.jsp?forum=57&thread=219443

camickra at 2007-7-8 8:26:43 > top of Java-index,Archived Forums,Swing...