Creating a Tic Tac Toe game. As of right now, the buttons have no purpose, and the game shouldn't work at all. All I am trying to do is set up the GUI for the game, which shows up sometimes I run it, but most of the time never shows up. I'm quite new to GUI for Java so any information would be helpful!
****EDIT: Figured it out! I had to do frame.setVisible(true)
after I created all the buttons, seemed to fix it.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.JOptionPane;
/**
* A class modelling a tic-tac-toe (noughts and crosses, Xs and Os) game in a very
* simple GUI window.
*
* @author Thomas Bryk
* @version December 4, 2016
*/
public class TicTacToe extends JFrame
{
private JFrame frame;
private JButton[][] buttons;
private JMenuBar menuBar;
private JMenuItem menuNew, menuQuit;
private JLabel label;
private JOptionPane pane;
/**
* Constructs a new Tic-Tac-Toe board and sets up the basic
* JFrame containing a JTextArea in a JScrollPane GUI.
*/
public TicTacToe()
{
super();
frame=new JFrame("Tic Tac Toe");
JMenu menu=new JMenu("Game");
label=new JLabel();
menuBar= new JMenuBar();
menuBar.add(menu);
menuNew= new JMenuItem("New");
menuNew.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,ActionEvent.CTRL_MASK));
menuNew.getAccessibleContext().setAccessibleDescription("Creates a new game of Tic Tac Toe");
menuQuit= new JMenuItem("Quit");
menuQuit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q,ActionEvent.CTRL_MASK));
menuQuit.getAccessibleContext().setAccessibleDescription("Quits the game of Tic Tac Toe");
menu.add(menuNew);
menu.add(menuQuit);
frame.setJMenuBar(menuBar);
frame.add(label);
frame=new JFrame("Tic Tac Toe");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(350,355);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
buttons=new JButton[3][3];
}
private void setUp()
{
JPanel game = new JPanel(new GridLayout(3,3));
JPanel panel = new JPanel(new BorderLayout());
frame.add(panel);
game.setVisible(true);
panel.setVisible(true);
game.setPreferredSize(new Dimension(300,300));
panel.setPreferredSize(new Dimension(325,425));
panel.add(game, BorderLayout.CENTER);
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
buttons[i][j] = new JButton();
buttons[i][j].setText("");
buttons[i][j].setVisible(true);
game.add(buttons[i][j]);
buttons[i][j].addActionListener(new ButtonListener());
}
}
}
public static void main (String[] args){
TicTacToe mainGame=new TicTacToe();
mainGame.setUp();
}
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent ev)
{
}
}
}