简体   繁体   中英

Can I switch the position of JPanels in an array of JPanels?

I have an array of JPanels that draws a Checkers-style board, some of those JPanels have black or yellow pieces on them, according to their position. I want to be able to move those pieces obviously.. is there a way to do that by switching their position in the array? I tried using the basic swap way in which I create a tmp and switch.. but that didn't work.. any help is much appreciated.

the swap trial:

JPanel tmp = board[4][3];
    board[4][3] = board[2][7];
    board[2][7] = tmp;

The visual position of some JPanel on the screen does not correlate to its position in some array (ie position in memory).

You could...

  • Swap the array locations as you described and additionally swap the visual positions (via getLocation() / setLocation() )

  • Leave both array position and visual positions unchanged, but swap the state (ie swap background colors or so).

some of those JPanels have black or yellow pieces on them, according to their position. I want to be able to move those pieces obviously..

  1. Use an opaque JLabel as the background for your checker board.
  2. Use Icons to represent the checker pieces.
  3. Move the Icons from label to label, instead of trying to swap the background component.

Have you tried repainting the entire frame?

I'm not sure what you did works as you expect. In case it doesn't you may want to try creating a method addComponents() in which you would (obviously :) ) add all the components in your frame.

When a change would be needed call removeAll(), call addComponents() again, and then validate() and repaint() :).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM