Search code examples
javaswingbuttonmouseeventmouse-listeners

Changing Color of JButton with mouseListener


Im trying to make a simple tictactoe game. To create the grid I used and array of JButtons.

mouseClicker m1 = new mouseClicker();//check for click

for (int i=0; i<9;i++) {//create buttons
            buttons[i] = new JButton();
            buttons[i].addMouseListener(m1);
            gameSpots.add(buttons[i]);
            
        }

In order to track a user's click I have a mouseListener for the buttons.

public class mouseClicker extends MouseAdapter{ 
        public void mousePressed(MouseEvent e) {
              System.out.println(e.getSource());
              System.out.println(e.getX()+", "+e.getY());
              System.out.println();  
           }
    }

With it currently I can print the source of each JButton clicked but I have no idea how to modify the corresponding button with this info (add an x to the button clicked for example). How could I use the JButton source to achieve this?


Solution

  • You could setText or setIcon:

    public class MouseClicker extends MouseAdapter {    
        public void mousePressed(MouseEvent e) {
            System.out.println(e.getSource());
            System.out.println(e.getX() + ", " + e.getY());
            System.out.println();
            ((JButton)e.getSource()).setText("X");
        }
    }