0

I have a JPanel 7width 9 height board. I can also place my pieces on top of the board. My problem now is how I will call the pieces: pseudo code: if(whero1 is on row 0 column 5 then....

code is below:

public class Board extends JPanel{
private static final String imageFolderPath = "src/resources/images/";
Dimension dimension = new Dimension(500, 500);
JPanel board;
JLabel piece;
MovePiece mp = new MovePiece(this);

public Board(){
  //set size of panel;
  this.setPreferredSize(dimension);
  this.addMouseListener(mp);
  this.addMouseMotionListener(mp);

  //create the Board
  board = new JPanel();
  board.setLayout(new GridLayout(9,7));
  board.setPreferredSize(dimension);
  board.setBounds(0, 0, dimension.width, dimension.height);
  this.add(board);

  for (int i = 0; i < 63; i++) {
    JPanel square = new JPanel(new BorderLayout());
    square.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
    board.add(square);
    square.setBackground(new Color(185, 156, 107));
  }
JLabel whero1 = new JLabel( new ImageIcon(imageFolderPath+"/pieces/bhero.png") );
  JPanel panel = (JPanel)board.getComponent(60);
  panel.add(whero1);

//I'm trying this, but i.m going nowhere
  int x =whero1.getParent().getX();
  int y = whero1.getParent().getY();
  System.out.println(x);
  System.out.println(y);
  /*if(x==0&&y==0){
      whero1.setIcon(new ImageIcon(imageFolderPath+"/pieces/bdg.png"));
  }*/
 }

}

user3266210
  • 299
  • 4
  • 15
  • Start accepting answers from previous questions (http://stackoverflow.com/questions/22297663/boards-squares-wont-appear) before asking new questions. – camickr Mar 11 '14 at 05:02
  • Side note, you should never explicitly need to use `src` in your path. If you are doing so, then it means your image is in the class path, and should be loaded as a resource and not as a file from the file system, which is what is happening when you pass a String to the `ImageIcon`. See more at the [Embedded-Resource](http://stackoverflow.com/tags/embedded-resource/info) tag wiki and see the link at the very bottom of it. – Paul Samsotha Mar 11 '14 at 05:10

1 Answers1

1

The easiest solution would be to maintain some kind of virtual model of the board. In this way you could simply update the state of the game and request that the UI update itself to reflect the state of the model.

Much simpler then trying to interrogate n-depth contains and convert to/from coordinate systems

nb: This...

int x =whero1.getParent().getX(); 
int y = whero1.getParent().getY();

Is going to return the pixel x/y position of the whereo1s parent's in relation to it's parent container, not convinced that this would really help at all

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366