I am making a tictactoe game where each board piece is represented by a JButton. When someone clicks the button the text is changed to "X" or "O". I am writing a reset function which resets the text in all the buttons to "". I am accessing all the buttons from an array using getComponents() method.
I just wondered what I am doing wrong because this bit compiles correctly
component[i].setEnabled(true);
but this bit does not
component[i].setText("");
I get a "cannot find symbol" error. Please have a look at the code below. I only included the code I thought was necessary.
JPanel board = new JPanel(new GridLayout(3, 3));
JButton button1 = new JButton("");
JButton button2 = new JButton("");
JButton button3 = new JButton("");
JButton button4 = new JButton("");
JButton button5 = new JButton("");
JButton button6 = new JButton("");
JButton button7 = new JButton("");
JButton button8 = new JButton("");
JButton button9 = new JButton("");
board.add(button1);
board.add(button2);
board.add(button3);
board.add(button4);
board.add(button5);
board.add(button6);
board.add(button7);
board.add(button8);
board.add(button9);
public void reset()
{
Component[] component = board.getComponents();
// Reset user interface
for(int i=0; i<component.length; i++)
{
component[i].setEnabled(true);
component[i].setText("");
}
// Create new board logic
tictactoe = new Board();
// Update status of game
this.updateGame();
}
getComponents ()
returns an array of Component
s, which does not have a setText(String)
method. You should either keep your JButton
instances as class members (this is the way I strongly suggest), and use them directly, or loop through all the Component
objects, check if it is a JButton
instance. If it is, explicitly cast it as a JButton
, then call setText(String)
on it. Eg
public void reset()
{
Component[] component = board.getComponents();
// Reset user interface
for(int i=0; i<component.length; i++)
{
if (component[i] instanceof JButton)
{
JButton button = (JButton)component[i];
button.setEnabled(true);
button.setText("");
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.