This week's book giveaway is in the OCPJP forum. We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line! See this thread for details.
If I wanted to have a background image for my whole Swing application, what are my options? Is there some sort of a standard approach for adapting to the window getting resized?
From my initial googling around, I see that there's a thing called glass pane that could be a solution but it seems like there's a lot of work involved in passing mouse/key events from the glass pane to the components behind the glass pane. Is that the case or am I just misinterpreting the examples I've found online?
What do you mean "my whole Swing application"? Do you just need a background image on a JPanel? If that is the case then just override the paintComponent method of your JPanel and draw the image there. Otherwise, I'll need a bit more info about what you need.
Thanks, Gregg. Yes, I'm talking about just having a JPanel with a background image. How would I go about rendering stuff on top of the background image? Is it so simple as to calling super.paintComponent()?
Yes, the first line in your paintComponent method will always be a call to super.paintComponents.
Joined: Jan 23, 2002
Thanks again. This seems to work:
Why does the call to super.paintComponents(Graphics) need to be the first line? Shouldn't that effectively draw all child elements and then draw the background image on top of them? It doesn't, but that's what my intuition would say.
Nope, it's because the paint() method is the real control behind all of this... it calls paintComponent() and then paintChildren(). Calling super.paintComponent() just works out a lot of basic Swing painting stuff for painting this component, things like setting opacity, default color, etc. [ April 11, 2005: Message edited by: Nathan Pruett ]
Write once, run anywhere, because there's nowhere to hide! - /. A.C.
I went back and read your initial post and realized you also had a question about resizing. As far as scaling the image on resize, you could have an internal ComponentListener class on the panel to listen for when it is resized, and scale and re-position the image accordingly.
Joined: Jan 23, 2002
Originally posted by Nathan Pruett: Nope, it's because the paint() method is the real control behind all of this... it calls paintComponent() and then paintChildren(). Calling super.paintComponent() just works out a lot of basic Swing painting stuff for painting this component, things like setting opacity, default color, etc.