Reputation: 751
I'm trying to code tic-tac-toe. I want the button to change to "X" when i click on it.
I'm not entirely done with my code.
But i want to see the button change text. But i don't see any change.
setText(); method looks right to me. :)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class tictac extends JFrame implements ActionListener{
JButton [][] game = new JButton[3][3];
JLabel head = new JLabel("Tic-Tac-Toe");
Font font = new Font("Time New Roman", Font.ITALIC, 20);
GridLayout grid = new GridLayout(3,3,0,0);
int row,column =0;
FlowLayout flow = new FlowLayout();
tictac(){
//setLayout(flow);
//add(head);
super("Tic-Tac-Toe");
setLayout(grid);
setVisible(true);
setDefaultCloseOperation(1);
setSize(500,500);
for (row =0; row<3;row++ ){
for(column =0; column <3;column++){
game[row][column]= new JButton("");
add(game[row][column]);
game[row][column].addActionListener(this);
}
}
}
public void actionPerformed(ActionEvent e){
Object source = e.getSource();
if (source == game[row][column])
game[row][column].setText("X");
System.out.println("X");
}
}
What I am doing wrongly?
Upvotes: 3
Views: 57
Reputation: 3729
You are using row
and column
wrongly.
Those values have been updated (both are now 3) in your double for loop, when you created those JButtons.
When you accessed them again in actionPerformed
, one problem is that it causes an ArrayIndexOutOfBoundsException.
Note: This is just a quick fix.
Declare # of rows (ROWS) and # of columns (COLS) as constants.
When there is an action performed, check each of these buttons using a double for loop.
Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class QuickTester {
public static void main (String [] args) {
TicTac tt = new TicTac();
}
}
class TicTac extends JFrame implements ActionListener{
JButton [][] game = new JButton[3][3];
JLabel head = new JLabel("Tic-Tac-Toe");
Font font = new Font("Time New Roman", Font.ITALIC, 20);
GridLayout grid = new GridLayout(3,3,0,0);
FlowLayout flow = new FlowLayout();
static final int ROWS = 3;
static final int COLS = 3;
TicTac(){
//setLayout(flow);
//add(head);
super("Tic-Tac-Toe");
setLayout(grid);
setVisible(true);
setDefaultCloseOperation(1);
setSize(500,500);
for (int row = 0; row < ROWS; row++ ){
for(int col = 0; col < COLS; col++){
game[row][col]= new JButton("");
add(game[row][col]);
game[row][col].addActionListener(this);
}
}
}
public void actionPerformed(ActionEvent e){
Object source = e.getSource();
for(int row = 0; row < ROWS; row++) {
for(int col = 0; col < COLS; col++) {
if (source == game[row][col])
game[row][col].setText("X");
System.out.println("X");
}
}
}
}
Output:
Upvotes: 3