0

I have a 30x30 GridLayout of JPanels. So each Cell in the 30x30 Frame is a JPanel with an Image. Aka Tiles on a map.

I need to move my character (red JPanel) around this map on keyPress.

How can I do this? I do not see a way of replacing a component in the GridLayout :S

Also, is there a better way than replacing the component because if I replace it, I'd have to keep track of the old component so that when the character moves to the next tile, it replaces the old component where the character used to be.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Brandon
  • 22,723
  • 11
  • 93
  • 186
  • You could use something like the frame glass pane or `JXLayer` to overlay your character on top of the grid pane. Might be better to allow you panels on the grid to custom paint the background and then "add" the character to it... – MadProgrammer May 06 '13 at 00:23

2 Answers2

1

GridLayout is not a good solution for your problem. Reason: GridLayout will always sort the components in the order you write "container.add(component)" statements. You can't put a component at a specific place, other than by inserting dummy components for all the places before.

You might want to try GridBagLayout.. In GridBagLayout, all you've to do on key event is to update the location of your dynamic panel and it shall be displayed on the top of the fixed panel at that location.. no need to remember old component

Mady
  • 653
  • 4
  • 11
  • Try writing some code and let us know if you are facing any problems with it You can read about GridBagLayout at: http://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html – Mady May 05 '13 at 23:56
  • I used the GridBagLayout after following this example: http://stackoverflow.com/questions/3695402/gridbaglayout-equally-distributed-cells How would I overlay my dynamic panel on it? – Brandon May 06 '13 at 00:31
  • I'm almost done with a sample program but have to rush.. would write you the code in couple of hours – Mady May 06 '13 at 01:18
  • :) I solved it. I only need to figure out when my character reaches the edge of my box. Should be fairly easy. – Brandon May 06 '13 at 02:39
  • Great, efforts well paid :) – Mady May 06 '13 at 03:14
1

How can I do this? I do not see a way of replacing a component in the GridLayout

Why do you need to replace the component? Just replace the image.

You would need to keep track of the last component and save its image. Then when you move to a new square, you:

a) restore the old image b) save the new image c) add your red image to the location.

camickr
  • 321,443
  • 19
  • 166
  • 288