我有一个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"));
}*/
}
}
答案 0 :(得分:1)
最简单的解决方案是维护董事会的某种虚拟模型。通过这种方式,您可以简单地更新游戏状态并请求UI更新自身以反映模型的状态。
更简单,然后尝试询问n深度包含并转换为/从坐标系
nb:这......
int x =whero1.getParent().getX();
int y = whero1.getParent().getY();
是否会返回whereo1
父级的像素x / y位置相对于它的父级容器,并不相信这会对它有所帮助