Search code examples
javauser-interfaceactionlistenerchess

Chess GUI - Getting 2 user clicks before calling a funtion - Java


I am trying to make a simple chess GUI, that consists only in a gridLayout where each square is made of a button, each button has an ActionListener and works independantly of the actual game, only "printing out" what is happening in the Board class.

private JButton[][] squares = new JButton[8][8];
private Color darkcolor = Color.decode("#D2B48C");
private Color lightcolor = Color.decode("#A0522D");
public ChessGUI(){
    super("Chess");
    contents = getContentPane();
    contents.setLayout(new GridLayout(8,8));

    ButtonHandler buttonHandler = new ButtonHandler();

    for(int i = 0; i< 8; i++){
        for(int j = 0;j < 8;j++){
            squares[i][j] = new JButton();
            if((i+j) % 2 != 0){
                squares[i][j].setBackground(lightcolor);
            }else{
                squares[i][j].setBackground(darkcolor);
            }
            contents.add(squares[i][j]);
            squares[i][j].addActionListener(buttonHandler);
            squares[i][j].setSize(75, 75);

        }
    }
    setSize(600, 600);
    setResizable(true);
    setLocationRelativeTo(null);
    setVisible(true);
}
private class ButtonHandler implements ActionListener{
    public void actionPerformed(ActionEvent e){
        Object source = e.getSource();
        for(int i = 0;i< 8; i++){
            for(int j = 0;j < 8;j++){
                if(source == squares[i][j]){
                    //Pass set of coordinates to game.Move(...)
                    return;
                }
            }
        }
    }
}

I need to pass 2 sets of coordinates, the "from" and the "to" to the game.Move(...) function(function that aplies game movement logic), where each set of coordinates is given by a click in a button.

How should i handle the fact that i need to wait for the user to make 2 clicks before calling the game.Move(...) function? It seems it can only pass 1 set of coordinates at a time.

Any help would be apricieated.


Solution

  • In game object you should probably have field variables that will store the from and to coordinates instead of passing them into game.move function. You can make a counter that starts at 0. When it is 0, it will process the "from" click (set the "from" variable in Game to the coordinate that was clicked), and when it is 1, it will process the "to" click (set "to" variable in Game), call move, and reset counter back to 0.