I'm working on a GUI for a chess game and I was wondering if there's any way to check for a series of clicks, for example: user clicks on jPanel THEN user clicks on another jPanel that exists in valid move array. I know I could use a variable to store some kind of state like "isSquareClicked = true" or something but I'd rather not unless that's the only way...
I don't see anything wrong with using JPanels. Here's my implementation:
First a ChessSquare, this represents one cell on the board:
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;
}
}
Now the main board panel:
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];
}
}
We keep a JPanel matrix to represent the board, and ChessSquare array to represent the current move. In isValidMove()
we check to see if the current move is complete (both squares have been clicked, thus the move array already has one element). Once a move is complete, we reset the move and start again.