I have a grid serving as the playing field for a simple Tower Defense game (it's not necessary to know the game genre, but it might help). I need each individual grid location to be a clickable object, hence why I'm trying to use JButtons. Each grid location has one out of many possible background sprites associated with it, which will be determined upon loading the given map. However, each grid location also can have an arbitrary-length hierarchy of objects contained inside of it, each with their own unique sprite (E.G: Each grid location may contain a Tower, which may contain a Weapon, and so on). These objects may or may not be present when the map is created, and will be both added and removed frequently after it has.
Unless I'm mistaken, a JButton may only contain a single Icon. My problem arises because I need to be able to layer several images on top of one another for each JButton, and I'm not entirely sure how to approach the problem.
I've done some research, and there are several ways that I've come up with to accomplish this:
- Combine the images and load them as a single Icon. Re-combine images and re-load a button whenever its grid location's contents change.
- Make each grid location a separate JPanel and override its paintComponent to draw the images from back to front. Use a transparent JButton on top of each grid location.
- A hybrid of the two: Have the front-most image be the JButton (the last to be drawn) and use an overridden paintComponent to draw the rest behind it.
I'm not experienced enough to know how well any of these would work. Are any of these non-starters or not worth the effort? What would be, in a more experienced programmer's opinion, the "best" solution in terms of expandability later? I don't need a working example or anything, I'd just like some advice as to which direction I should head in. I should be able to figure out a crude implementation on my own.
(I'm also worried about how I'm going to draw enemies at arbitrary locations on top of these grid locations, but I'll figure that out when I get there.)
I'd be happy to elaborate or try to whip up a code example for any of the above.