Unable to update JButton in Java Swing

233 views Asked by At

I am trying to build a TicTacToe game in Java and using Swing for GUI. As I doesn't know much Swing, I am using JButton for creating tiles. Initially all the tiles are blank. Now, when a user clicks on an empty tile i.e. an empty button, I want to put a "X" or "O" depicting image on that button. But I'm unable to do that. Any help is appreciated. I already tried things, but not working.

Here is my code:

/* Showing only required code */

public void run(){

        /* Creating blank JButtons */
         for (int i = 0; i < 3; i++) {
             for(int j = 0; j<3; j++){
                tile[i][j] = new JButton("");
                tile[i][j].setActionCommand("Tile: (" + String.valueOf(i) + "," +   String.valueOf(i) + ")"); 
                /* tile[i][j] has setActionCommand as "Tile: (i,j)" */

                panel.add(tile[i][j]);
             }
         }
         panel.setBounds(140, 170, 300, 300);
         add(panel);
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         setVisible(true);  
 }


 /* HERE LIES THE MAIN PROBLEM AS BUTTONS ARE NOT UPDATED AS EXPECTED*/

 public void actionPerformed(ActionEvent e) {
     // when lefttop corner tile is clicked
     if("Tile: (0,0)".equals(e.getActionCommand())){
         if(tileDone[0][0] == false){ // checking if its still empty
             if(currentPlayer.equals("X")){ // checking if current player is "X"
                tile[0][0] = new JButton(new ImageIcon("/home/kaustubh/Desktop /java/TicTacToe/X.png"));
                 panel.add(tile[0][0]);
                 panel.repaint();
                 this.repaint();
                 System.err.println();
             }
             else{
                tile[0][0] = new JButton(new ImageIcon("/home/kaustubh/Desktop/java/TicTacToe/O.png"));
                panel.add(tile[0][0]);
                panel.repaint();
                this.repaint();
                System.err.println();
            }
            tileDone[0][0] = false;
        }
    }

}

}

1

There are 1 answers

0
martinez314 On BEST ANSWER

It's unclear why you are adding the button again in actionPerformed(). If you plan to add the button again, you first need to remove the old one. Instead, you probably mean to just update the icon.

 public void actionPerformed(ActionEvent e) {
     // when lefttop corner tile is clicked
     if("Tile: (0,0)".equals(e.getActionCommand())){
         if(tileDone[0][0] == false){ // checking if its still empty
             if(currentPlayer.equals("X")){ // checking if current player is "X"

                // here...
                tile[0][0].setIcon(new ImageIcon("/home/kaustubh/Desktop /java/TicTacToe/X.png"));
                //panel.add(tile[0][0]);  // remove this

                 panel.repaint();
                 this.repaint();
                 System.err.println();
             }