I need a Jbutton that can change the text in other Jbuttons when clicked.
:(sweat): Yeah I know, I'm kinda new to JAVA. Anyway, I've been trying to put together a tictactoe game for a homework assignment (tight deadline) and here's the code I have so far:
Code:
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class tictactoe {
public static final int FRAME_WIDTH = 700;
public static final int FRAME_HEIGHT = 200;
public static void main(String[] args)
{
int slots = 9;
JButton[] gameButton = new JButton[9];
JPanel ticTacToeBoard = new JPanel();
ticTacToeBoard.setLayout(new GridLayout(3, 3));
for (int i = 0; i < slots; i++)
{
gameButton[i] = new JButton();
ticTacToeBoard.add(gameButton[i]);
gameButton[i].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
((JButton)e.getSource()).setText("x");
}
});
JButton clearButtons = new JButton("New Game");
clearButtons.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
gameButton[i].setText("");
}
});
JButton exit = new JButton("Exit");
JPanel rightPanel = new JPanel();
JLabel wonLabel = new JLabel();
rightPanel.setLayout(new GridLayout(1, 3));
rightPanel.add(wonLabel);
rightPanel.add(clearButtons);
rightPanel.add(exit);
JFrame mainFrame = new JFrame();
mainFrame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
mainFrame.setVisible(true);
mainFrame.setLayout(new GridLayout(1,2));
mainFrame.add(ticTacToeBoard);
mainFrame.add(rightPanel);
}
}
}
Basically, I need the clearButtons button to clear out the text for each gameButton but I get a lot of "must be declared final" errors at line 36. Can somebody help? Thanks.
Re: I need a Jbutton that can change the text in other Jbuttons when clicked.
The problem is that you have an inner class, the anonymous ActionListener, that is trying to use local variables, the gameButton array, and this is not allowed if the local variable is not final (this is because inner classes are really separate classes that need to make copies of all local variables...). I have 3 possible solutions for you:
The easiest, just declare the local variable final (if you can get away with this -- and here you can):
Code:
final JButton[] gameButton = new JButton[9];
A better solution, don't use a local gameButton array variable, but rather make the gameButton array a static array of the class.
The best solution: get all that code out of your main method and create a true OOPs GUI program, one that does not use static variables and methods (except for a very small main method) and make the gameButton array a non-static field of the class.
Re: I need a Jbutton that can change the text in other Jbuttons when clicked.
Thanks...I added the "final" and rearranged a few things; that did the job.