Im trying to make a simple Tic Tac Toe
game right now, i created a JFrame with the Grid Layout and added 9 buttons to it. Now uppon clicking one of those buttons i want to change the Icon of it to be either a cross or a circle, but it just doesnt do anything on click
@Override
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == this)
{
if (counter%2 == 0)
{
ImageIcon cross = new ImageIcon("Cross.png");
this.setIcon(cross);
}
if (counter%2 == 1)
{
ImageIcon circle = new ImageIcon("Circle.png");
this.setIcon(circle);
}
counter ;
}
}
The actionPerformed
method does work with a simple System.out.println()
statement
Thanks in Advance!
CodePudding user response:
You have to understand the meaning of e.getSource()
, it's return all properties of button. Your condition e.getSource() == this
return false that is a problem. You have to set image icon like new javax.swing.ImageIcon(getClass().getResource("path/img_name"))
.
Here down is generic code implementation so the logic will work on any of the nine buttons:
public void jButton1ActionPerformed(ActionEvent e)
{
JButton button = (JButton)e.getSource();
if(counter % 2 == 0)
{
button.setIcon(new javax.swing.ImageIcon(getClass().getResource("Cross.png")));
}
else
{
button.setIcon(new javax.swing.ImageIcon(getClass().getResource("Circle.png")));
}
counter ;
}