tags:

views:

228

answers:

1

I have a JPanel onto which I'm trying to add some buttons. I have a bitmap background image onto which I'm supposed to draw the buttons. I have images for all the buttons. I need the background to scale with the buttons and the spacing to be correct. Is there a clean way to do this or is this going to be painful?

Thanks

+1  A: 

First the JPanel with a background image is easy. Derive your own panel from JPanel, add an Image field. Override the paintComponent() method to do a drawImage() using the image stored in the field.

Second the buttons. Derive you own button, add image in constructor, and use setIcon() to put it on the button. use setPressedIcon(), ... and so on to add additional images for the various button states.

Lastly the scaling, it is not clear to me what you want. The drawImage() can scale the image, so that is no problem. You can position the buttons when the JPanel is resized by adding a listener. Then you can reposition the buttons the x, y values should be calculated as a % of the width and height of the panel. You could even rescale the buttons so that the width /height ratio is the same of the panels ratio.

So yes, there is a clean way to do it.

Bruno Ranschaert
Why would you use a listener for repositioning the button? Just using the appropriate LayoutManager will take care of this for you and avoid any nasty redraw issues
MrWiggles
Because of the scaling. I assume that the buttons are somewhat related to the background image and should adjust relative to the size of the background. This is relatively easy to accomplish using a listener to the background panel's size and recalculating the position of the buttons. I cannot immediately think of a layout manager doing this. But I admit that my assumption can be wrong, and in that case a layout manager might be a better solution.
Bruno Ranschaert