我有一个JPanel 7width 9高度板。我也可以将自己的作品放在木板上。我现在的问题是如何称呼这些东西:
伪代码:
if(whero1位于第0行第5列,然后...

代码如下:

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"));
  }*/
 }


}

最佳答案

最简单的解决方案是维护板的某种虚拟模型。这样,您可以简单地更新游戏的状态并请求UI更新自身以反映模型的状态。

然后比尝试查询n深度包含和转换坐标系简单得多

nb:这个...

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


将要返回whereo1父级相对于其父级容器的像素x / y位置,而不确信这真的有帮助

09-10 12:48
查看更多