Hi guys, I am in desperate need of help. I'm not exactly sure how to fix this or how to pass contentpanes correctly. Here is my code for gameboard.java:
import javax.swing.*;
public class GameBoard implements ActionListener {
private int[][] winSlots = new int[][] {
{0, 1, 2}, {3, 4, 5}, {6, 7, 8}, //horizontal wins
{0, 3, 6}, {1, 4, 7}, {2, 5, 8}, //virticle wins
{0, 4, 8}, {2, 4, 6} //diagonal wins
};
private JFrame frame = new JFrame("Tic Tac Toe");
private JButton buttons[] = new JButton[9];
private int count = 0;
private String player = "";
private boolean win = false;
public GameBoard(){
frame.setSize(300,300);
//frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(3,3));
//much easier. <3 for loops
for(int i=0; i<9; i++){
buttons[i] = new JButton();
frame.add(buttons[i]);
buttons[i].addActionListener(this);
}
//frame.setVisible(true);
}
public void actionPerformed(ActionEvent act) {
count++;
if(count % 2 == 0){
player = "O";
} else {
player = "X";
}
JButton pressedButton = (JButton)act.getSource();
pressedButton.setText(player);
pressedButton.setEnabled(false);
for(int i=0; i<8; i++){
if( buttons[winSlots[i][0]].getText().equals(buttons[winSlots[i][1]].getText()) &&
buttons[winSlots[i][1]].getText().equals(buttons[winSlots[i][2]].getText()) &&
buttons[winSlots[i][0]].getText() != ""){
win = true;
}
}
if(win == true){
JOptionPane.showMessageDialog(null,player + " wins!");
System.exit(0);
} else if(count == 9 && win == false){
JOptionPane.showMessageDialog(null,"Tie Game!");
System.exit(0);
}
}
public Container getContentPane(){
return frame.getContentPane();
}
//public static void main(String[] args){
//GameBoard starter = new GameBoard();
//}
}
Now this works perfectly on it's own without a driver class (commented out stand-a-lone parts), but once I edit it to make it work with the driver class, it won't work. The driver class is provided to me by my professor.
Driver Class:
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import java.awt.event.*;
public class TicTacToeDriver {
public static void main(String[] args)
{
GameBoard b = new GameBoard ();
JFrame frame = new JFrame (" Tic Tac Toe Board");
frame.getContentPane().add(b);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack ();
frame.setVisible (true);
}
}