我正在为国际象棋游戏开发 GUI,我想知道是否有任何方法可以检查一系列点击,例如:用户点击 jPanel THEN 用户点击另一个存在于有效移动数组中的 jPanel。我知道我可以使用变量来存储某种状态,例如“isSquareClicked = true”之类的,但我宁愿不这样做,除非这是唯一的方法......
3 回答
我认为使用 JPanels 没有任何问题。这是我的实现:
首先是 ChessSquare,它代表棋盘上的一个单元:
public class ChessSquare extends JPanel{
int x,y;
public ChessSquare(int x, int y){
super();
this.setPreferredSize(new Dimension(50,50));
this.setBorder(BorderFactory.createLineBorder(Color.black));
this.x = x;
this.y = y;
}
}
现在主板面板:
public class ChessPanel extends JPanel{
JPanel positions[][] = new JPanel[8][8];
ChessSquare move[] = new ChessSquare[2];
public ChessPanel(){
initComponents();
}
private void initComponents(){
setLayout(new GridLayout(8,8));
for(int i=0;i<positions.length;i++){
for(int j=0;j<positions[i].length;j++){
ChessSquare square = new ChessSquare(i,j);
square.addMouseListener(new MouseListener(){
public void mouseClicked(MouseEvent me) {
ChessSquare cs = (ChessSquare)me.getComponent();
if(isValidMove(cs)){
System.out.println("Valid move!");
System.out.println("x1: "+move[0].x+" y1: "+move[0].y);
System.out.println("x2: "+move[1].x+" y2: "+move[1].y);
System.out.println("");
resetMove();
}
}
//Other mouse events
});
positions[i][j] = square;
add(square);
}
}
}
private boolean isValidMove(ChessSquare square){
//here you would check if the move is valid.
if(move[0] == null){
move[0] = square;
return false; //first click
}else{
move[1] = square;
}
//Other chess rules go here...
return true;
}
private void resetMove(){
move = new ChessSquare[2];
}
}
我们用一个 JPanel 矩阵来表示棋盘,用 ChessSquare 数组来表示当前的移动。在isValidMove()
我们检查当前移动是否完成(两个方块都被点击,因此移动数组已经有一个元素)。移动完成后,我们重置移动并重新开始。
据我所知,Java 中没有这样的东西。
但:
1)据我了解,您使用 8x8 JPanels 的字段为游戏创建字段?恕我直言,这是不好的方式。如果我是你,我会使用一个面板来创建字段 - 通过在上面绘制所有内容(单元格、图形等)。这更简单,创建更快,更容易使用。
2)回到你的问题。如果您有一个字段面板 - 您只需要记住 2 对坐标:第一次单击的位置和第二次单击的位置。在您的情况下 - 单击面板上的 2 个指针就足够了。;)
希望这有帮助:)
我同意 imp - 您可能想要一个 JPanel 并在该面板上绘制所有内容。
话虽如此,如果有人已经用 8x8 JPanel 实现了棋盘并告诉我使用它,我可能会尝试将 8x8 JPanel 放在 JLayeredPane 中,然后将单个透明 JPanel 放在一切之上以处理所有鼠标点击。
尽管如此,这种方法仍需要您进行点算术以找出正在单击的单元格,而且我猜测使用 8x8 JPanel 的目的是您首先要避免进行这种算术。