I had spent two days in solving this problem but I have not found any solution.
I will put some easy code.
There is JFrame with some menu Bar, JPanels, but we focus on 2 options:
"Create Server"
"Close connection"
When I create server, on JPanel I draw checkerboard, and when I close connection, JPanel is clean, but the problem begins when I want to create server one more time, JPanel shows nothing.
I checked the input JPanel, and I put required JPanel before recreate server - nothing
I thought maybe it's gameControl, but I use it in other cases and it works also.
If anybody wants to try:
Here is entire project: http://bycniebytem.cba.pl/checkers.rar
Problem is inside the Checkers.java class,
But I'm waiting for your advices! Thanks!
hostServer.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
hostServer.setEnabled(false);
closeConnection.setEnabled(true);
server = new Server();
try
{
JPanel networkPanel = new JPanel();
player1 = new Player(1,boardSize, fieldSize);
player1.gameControl.setBounds(10, 10, boardSize*fieldSize + 10, boardSize*fieldSize + 10);
player1.gameControl.setSize(boardSize*fieldSize, boardSize*fieldSize);
player1.gameControl.addMouseListener(player1.gameControl);
player1.gameControl.addMouseMotionListener(player1.gameControl);
player1.gameControl.setFocusable(true);
player1.gameControl.setPreferredSize(new Dimension(boardSize*fieldSize,boardSize*fieldSize));
player1.connectWithServer(server.serverSocket.getInetAddress().getHostAddress());
JPanel votePanel = new JPanel();
JRadioButton whiteRadioButton = new JRadioButton("White");
JRadioButton blackRadioButton = new JRadioButton("Black");
blackRadioButton.setBounds(1, 1, 100, 30);
whiteRadioButton.setBounds(1, blackRadioButton.getHeight() + 5, 100, 30);
JButton bReady = new JButton("Ready");
bReady.setBounds(1, whiteRadioButton.getHeight() + 5, 100, 30);
ButtonGroup radioGroup = new ButtonGroup();
radioGroup.add(whiteRadioButton);
radioGroup.add(blackRadioButton);
votePanel.add(blackRadioButton);
votePanel.add(whiteRadioButton);
votePanel.add(bReady);
votePanel.setBounds(player1.gameControl.getWidth() + 10, 10, blackRadioButton.getWidth(), blackRadioButton.getHeight() * 3);
votePanel.setPreferredSize(new Dimension(blackRadioButton.getWidth(), player1.gameControl.getHeight()));
setSize(boardSize * fieldSize + votePanel.getWidth() + 50, getJMenuBar().getHeight() + boardSize * fieldSize + 20);
networkPanel.add(player1.gameControl);
networkPanel.add(votePanel);
add(networkPanel);
setContentPane(networkPanel);
}
catch(IOException ex)
{
}
}
});
And close connection
closeConnection.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try
{
if(server != null)
{
if(server.getPlayerBlackSocket() != null)
{
server.sendMessage(server.getPlayerBlackSocket(), "closeConnection");
server.getPlayerBlackSocket().close();
}
if(server.getPlayerWhiteSocket() != null)
{
server.sendMessage(server.getPlayerWhiteSocket(), "closeConnection");
server.getPlayerWhiteSocket().close();
}
if(server.getServerSocket() != null)
{
server.getServerSocket().close();
}
}
}
catch (IOException ex)
{
}
player1.isOpenedConnection = false;
JPanel pane = (JPanel) getContentPane();
pane.removeAll();
remove(pane);
JPanel Pan = new JPanel();
JLabel label = new JLabel("label"); // just to test if jpanel can show and it shows
label.setBounds(10,10,100,30);
Pan.add(label);
setContentPane(Pan);
revalidate();
repaint();
closeConnection.setEnabled(false);
hostServer.setEnabled(true);
}
});
I have a maze that I need to get a ball to move through, but I don't know what code I need to use to move the image of the ball around the maze.
I have been given a hint that I need to swap images round.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CBallMaze extends JFrame implements ActionListener
{
//Below is where I have declared all the different objects I have used throughout my program
private JButton buttonRight, buttonLeft, buttonUp, buttonDown, buttonTL, buttonTR, buttonBL, buttonBR, buttonCenter, optionOne, optionTwo, optionThree, optionExit, scenarioAct, scenarioRun, scenarioReset, compassPH;
private JButton [] game = new JButton [208];
private JPanel panelCentre, panelRight, panelBottom, buttonPanel, compassPanel, optionsPanel, selectionPanel, panelAct, panelRun, panelReset, panelSlider;
private JTextField optionTF, squareTF, directionTF;
private JLabel option, square, direction, compassDirection;
private JSlider speedSlider;
private String firstOption = "1", secondOption = "2", thirdOption = "3", upDirection = "North", rightDirection = "East", downDirection = "South", leftDirection = "West";
private int i;
private int[] map = new int[]
{
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,
3,1,3,3,3,1,3,3,3,1,3,3,3,3,3,3,
3,1,3,3,3,1,3,3,3,1,3,3,3,3,3,3,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
3,3,1,3,3,3,1,3,3,3,3,1,3,3,3,3,
3,3,1,3,3,3,1,3,3,3,3,1,3,3,3,3,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
3,1,3,3,3,1,3,3,3,1,3,3,3,3,3,3,
3,1,3,3,3,1,3,3,3,1,3,3,3,3,3,3,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
3,3,1,3,3,3,1,3,3,3,3,1,3,3,3,3,
3,3,1,3,3,3,1,3,3,3,3,1,3,3,3,3,
4,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
};
final ImageIcon iconCompassNorth = new ImageIcon("north.jpg");
final ImageIcon iconCompassWest = new ImageIcon("west.jpg");
final ImageIcon iconCompassSouth = new ImageIcon("south.jpg");
final ImageIcon iconCompassEast = new ImageIcon("east.jpg");
ImageIcon iconReset = new ImageIcon("Reset.jpg");
ImageIcon iconRun = new ImageIcon("Run.jpg");
ImageIcon iconAct = new ImageIcon("Act.jpg");
ImageIcon iconSand, iconWhite, iconBall, iconEnd;
public CBallMaze(String title) {
super(title);
}
public static void main(String[] args)
{
CBallMaze cBallMaze = new CBallMaze("CBallMaze Ball Maze Application");
cBallMaze.setSize(775, 650);
cBallMaze.createGUI();
cBallMaze.setVisible(true);
}
private void createGUI()
{
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container window = getContentPane();
window.setLayout(new BorderLayout() );
//Panels
panelCentre = new JPanel();
panelCentre.setPreferredSize(new Dimension(625, 450));
panelCentre.setBackground(Color.BLACK);
window.add(panelCentre);
panelCentre.setLayout(new GridLayout(13, 16));
panelRight = new JPanel();
panelRight.setPreferredSize(new Dimension(180, 450));
panelRight.setBackground(Color.WHITE);
window.add(panelRight, BorderLayout.EAST);
optionsPanel = new JPanel();
optionsPanel.setPreferredSize(new Dimension(150, 100));
optionsPanel.setBackground(Color.WHITE);
panelRight.add(optionsPanel, BorderLayout.EAST);
buttonPanel = new JPanel();
buttonPanel.setPreferredSize(new Dimension(175, 100));
buttonPanel.setBackground(Color.WHITE);
panelRight.add(buttonPanel, BorderLayout.EAST);
selectionPanel = new JPanel();
selectionPanel.setPreferredSize(new Dimension(175, 150));
selectionPanel.setBackground(Color.WHITE);
panelRight.add(selectionPanel, BorderLayout.EAST);
ImageIcon cw = new ImageIcon("west.jpg");
compassPanel = new JPanel();
compassPanel.setPreferredSize(new Dimension(175, 300));
compassPanel.setBackground(Color.WHITE);
panelRight.add(compassPanel, BorderLayout.EAST);
panelBottom = new JPanel();
panelBottom.setPreferredSize(new Dimension(875, 50));
panelBottom.setBackground(Color.WHITE);
window.add(panelBottom, BorderLayout.SOUTH);
panelAct = new JPanel();
panelAct.setPreferredSize(new Dimension(125, 40));
panelAct.setBackground(Color.WHITE);
panelBottom.add(panelAct, BorderLayout.SOUTH);
panelRun = new JPanel();
panelRun.setPreferredSize(new Dimension(125, 40));
panelRun.setBackground(Color.WHITE);
panelBottom.add(panelRun, BorderLayout.SOUTH);
panelReset = new JPanel();
panelReset.setPreferredSize(new Dimension(125, 40));
panelReset.setBackground(Color.WHITE);
panelBottom.add(panelReset, BorderLayout.SOUTH);
panelSlider = new JPanel();
panelSlider.setPreferredSize(new Dimension(200, 40));
panelSlider.setBackground(Color.WHITE);
panelBottom.add(panelSlider, BorderLayout.SOUTH);
//Displays
option = new JLabel("Option: ");
optionsPanel.add(option, BorderLayout.LINE_START);
option.setEnabled(true);
option.setForeground(Color.BLACK);
option.setHorizontalAlignment(JLabel.LEFT);
optionTF = new JTextField("1");
optionsPanel.add(optionTF, BorderLayout.LINE_END);
optionTF.setEnabled(true);
optionTF.setPreferredSize(new Dimension(50, 25));
optionTF.setHorizontalAlignment(JTextField.CENTER);
square = new JLabel("Square: ");
optionsPanel.add(square, BorderLayout.LINE_START);
square.setEnabled(true);
square.setForeground(Color.BLACK);
square.setHorizontalAlignment(JLabel.LEFT);
squareTF = new JTextField("");
optionsPanel.add(squareTF, BorderLayout.LINE_END);
squareTF.setEnabled(true);
squareTF.setPreferredSize(new Dimension(50, 25));
squareTF.setHorizontalAlignment(JTextField.CENTER);
direction = new JLabel("Direction: ");
optionsPanel.add(direction, BorderLayout.LINE_START);
direction.setEnabled(true);
direction.setForeground(Color.BLACK);
direction.setHorizontalAlignment(JLabel.LEFT);
directionTF = new JTextField("Still");
optionsPanel.add(directionTF, BorderLayout.LINE_END);
directionTF.setEnabled(true);
directionTF.setPreferredSize(new Dimension(50, 25));
directionTF.setHorizontalAlignment(JTextField.CENTER);
//buttons
buttonTL = new JButton("");
buttonPanel.add(buttonTL);
buttonTL.setPreferredSize(new Dimension(45, 25));
buttonTL.setEnabled(false);
buttonUp = new JButton("^");
buttonPanel.add(buttonUp);
buttonUp.setPreferredSize(new Dimension(45, 25));
buttonUp.addActionListener(this);
buttonUp.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
directionTF.setText(upDirection);
compassDirection.setIcon(iconCompassNorth);
}
});
buttonTR = new JButton("");
buttonPanel.add(buttonTR);
buttonTR.setPreferredSize(new Dimension(45, 25));
buttonTR.setEnabled(false);
buttonLeft = new JButton("<");
buttonPanel.add(buttonLeft);
buttonLeft.setPreferredSize(new Dimension(45, 25));
buttonLeft.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
directionTF.setText(leftDirection);
compassDirection.setIcon(iconCompassWest);
}
});
buttonCenter = new JButton("");
buttonPanel.add(buttonCenter);
buttonCenter.setPreferredSize(new Dimension(45, 25));
buttonCenter.setEnabled(false);
buttonRight = new JButton(">");
buttonPanel.add(buttonRight);
buttonRight.setPreferredSize(new Dimension(45, 25));
buttonRight.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
directionTF.setText(rightDirection);
compassDirection.setIcon(iconCompassEast);
}
});
buttonBL = new JButton("");
buttonPanel.add(buttonBL);
buttonBL.setPreferredSize(new Dimension(45, 25));
buttonBL.setEnabled(false);
buttonDown = new JButton("v");
buttonPanel.add(buttonDown);
buttonDown.setPreferredSize(new Dimension(45, 25));
buttonDown.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
directionTF.setText(downDirection);
compassDirection.setIcon(iconCompassSouth);
}
});
buttonBR = new JButton("");
buttonPanel.add(buttonBR);
buttonBR.setPreferredSize(new Dimension(45, 25));
buttonBR.setEnabled(false);
optionOne = new JButton("Option One");
selectionPanel.add(optionOne);
optionOne.setPreferredSize(new Dimension(125, 25));
optionOne.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
optionTF.setText(firstOption);
}
});
optionTwo = new JButton("Option Two");
selectionPanel.add(optionTwo);
optionTwo.setPreferredSize(new Dimension(125, 25));
optionTwo.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
optionTF.setText(secondOption);
}
});
optionThree = new JButton("Option Three");
selectionPanel.add(optionThree);
optionThree.setPreferredSize(new Dimension(125, 25));
optionThree.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
optionTF.setText(thirdOption);
}
});
optionExit = new JButton("Exit");
selectionPanel.add(optionExit);
optionExit.setPreferredSize(new Dimension(125, 25));
scenarioAct = new JButton("Act");
scenarioAct.setIcon(iconAct);
panelAct.add(scenarioAct);
scenarioAct.addActionListener(this);
scenarioRun = new JButton("Run");
scenarioRun.setIcon(iconRun);
panelRun.add(scenarioRun);
scenarioRun.addActionListener(this);
scenarioReset = new JButton("Reset");
scenarioReset.setIcon(iconReset);
panelReset.add(scenarioReset);
scenarioReset.addActionListener(this);
JSlider speedSlider = new JSlider(JSlider.HORIZONTAL, 0, 50, 25);
speedSlider.setMajorTickSpacing(10);
speedSlider.setMinorTickSpacing(5);
speedSlider.setPaintTicks(true);
speedSlider.setBackground(Color.WHITE);
speedSlider.setLabelTable(speedSlider.createStandardLabels(10));
panelSlider.add(speedSlider);
compassDirection = new JLabel();
compassPanel.add(compassDirection);
try
{
iconSand = new ImageIcon("sand.jpg");
}
catch (Exception e)
{
System.err.println("Sand Icon "+e);
}
try
{
iconBall = new ImageIcon("sand60x60.png");
}
catch (Exception e)
{
System.err.println("Ball Icon "+e);
}
try
{
iconWhite = new ImageIcon("white32x32.jpg");
}
catch (Exception e)
{
System.err.println("White Icon "+e);
}
try
{
iconEnd = new ImageIcon("sandstone.jpg");
}
catch (Exception e)
{
System.err.println("End Icon"+e);
}
for (i=0;i<208;i++)
{
game[i] = new JButton ();
if(map[i]==1)
{
game[i].setIcon(iconSand);
}
if(map[i]==2)
{
game[i].setIcon(iconBall);
}
if(map[i]==3)
{
game[i].setIcon(iconWhite);
}
if(map[i]==4)
{
game[i].setIcon(iconEnd);
}
game[i].setBorder(null);
game[i].setPreferredSize(new Dimension(32, 32));
game[i].addActionListener(this);
panelCentre.add(game[i]);
}
}
public void actionPerformed(ActionEvent arg0)
{
}
}
Try this (works for me):
After this line panelCentre.add(game[i]); enter this:
game[i].addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
System.out.println(e.getKeyCode());
switch (e.getKeyCode()) {
case KeyEvent.VK_RIGHT:
System.out.println("right...");
break;
case KeyEvent.VK_LEFT:
System.out.println("left...");
break;
case KeyEvent.VK_DOWN:
System.out.println("down...");
break;
case KeyEvent.VK_UP:
System.out.println("up...");
}
}
});
This should print out the direction you typed with the arrow keys.
Here is the answer to the question
How to move the ball in the maze
https://gist.github.com/ad78d37918de6320733b
Note that you should use an own KeyEventDispatcher because otherwise you would have to attach the KeyListener to ALL components in your WHOLE GUI (see this post)
Anyway, as #chris pointed out, a ball object and another data structure than array would make your assignment easier :)
i´ve been trying to refresh de JTable after inserting data in MySql, but i cant manage to make it work.
The data is filled in the agregar JPanel and saved after clicking a button, checking in the mysql console, the data is added to the database, but when i open the table it doesn´t update unless i restart the program.
This is My code:
public class verTodos extends JPanel {
contactoDAO dao = new contactoDAO();
List<contacto> contactos = dao.getAll();
private JTable table;
public verTodos() {
String[] colName = { "Id", "Nombre", "Apellido", "Telefono",
"Direccion", "Email", "Rubro1", "Rubro2", "Rubro3" };
Object[][] obj = new Object[contactos.size()][10];
for (int i = 0; i < contactos.size(); i++) {
contacto c = contactos.get(i);
obj[i][0] = c.getId();
bj[i][1] = c.getNombre();
obj[i][2] = c.getApellido();
obj[i][3] = c.getTelefono();
obj[i][4] = c.getDireccion();
obj[i][5] = c.getEmail();
obj[i][6] = c.getRubro1();
obj[i][7] = c.getRubro2();
obj[i][8] = c.getRubro3();
setBounds(100, 100, 800, 300);
}
DefaultTableModel contactTableModel = new DefaultTableModel(obj,colName);
table = new JTable(contactTableModel);
setLayout(new BorderLayout(0, 0));
contactTableModel.fireTableDataChanged();
contactTableModel.setColumnIdentifiers(colName);
add(table.getTableHeader(), BorderLayout.NORTH);
JScrollPane scrollPane = new JScrollPane();
add(scrollPane, BorderLayout.CENTER);
scrollPane.setViewportView(table);
repaint();
}
}
this is the main screen that contains the JPanels:
public class principal extends JFrame {
JFrame frame = new JFrame();
JPanel container = new JPanel();
CardLayout cl = new CardLayout();
private final JMenuBar menuBar = new JMenuBar();
/.....
.....
private final JMenuItem mntmVerTodos = new JMenuItem("Ver todos");
private final JMenuItem mntmAgregar = new JMenuItem("Agregar");
agregar ag = new agregar();
verTodos ver = new verTodos();
...
...
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new principal();
}
});
}
public principal() {
textField.setMaximumSize(new Dimension(300, 500));
textField.setBounds(new Rectangle(0, 0, 30, 0));
textField.setColumns(10);
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
int X = (screen.width / 2) - (1366 / 2);
int Y = (screen.height / 2) - (720 / 2);
frame.setBounds(X, Y, 1363, 720);
container.setLayout(cl);
ver.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
container.add(ver, "ver");
container.add(ag, "ag");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
frame.getContentPane().add(container);
frame.setJMenuBar(menuBar);
menuBar.add(mnNewMenu);
cl.show(container, "ver");
mntmVerTodos.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cl.show(container, "ver");
}
});
mnContactos.add(mntmVerTodos);
mnContactos.add(mntmAgregar);
mntmModificar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cl.show(container, "mod");
}
});
menuBar.add(btn);
frame.setVisible(true);
}
}
You need to repopulate your model once the database has been updated. Add a refresh button that when clicked, updates contactTableModel
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class tictac2 implements ActionListener{
static boolean blue = true; //used to keep track of turns. if true, blue's turn, else, red's turn. Blue is x, red is o
static int bWins = 0, rWins = 0;
JFrame mainWindow;
JPanel board;
JButton[] buttons;
public tictac2() {
init();
}
private void init() {
try { //Try to set the L&F to system
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e) {
e.toString();
System.out.println("Couln't change look and feel. Using default");
}
mainWindow = new JFrame("Tic Tac Toe!");
mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainWindow.setVisible(true);
mainWindow.setSize(800,600);
JMenuBar bar = new JMenuBar(); //Menu bar init
JMenu file = new JMenu("File");
JMenuItem newGame = new JMenuItem("New Game"), quitItem = new JMenuItem("Quit");
file.add(newGame);
file.addSeparator();
file.add(quitItem);
bar.add(file);
mainWindow.getContentPane().add(bar, BorderLayout.NORTH); //Menu bar done
newGameBoard(); //New Game Board
JPanel infoPane = new JPanel();
infoPane.setLayout(new GridLayout(1,3));
JLabel turn = new JLabel("Blue Player's Turn"), spacer = new JLabel(""), score = new JLabel("Blue: 0, Red: 0");
infoPane.add(turn);
infoPane.add(spacer);
infoPane.add(score);
mainWindow.getContentPane().add(infoPane,BorderLayout.SOUTH);
newGame.addActionListener(this); //Add action listeners
quitItem.addActionListener(this);
}
private void newGameBoard() {
board = new JPanel(); //Game Pane init
board.setLayout(new GridLayout(3,3));
buttons = new JButton[9];
for (int i = 0; i <9; i++){
buttons[i] = new JButton("");
buttons[i].setOpaque(true);
buttons[i].setFont(new Font("sansserif", Font.BOLD, 90));
board.add(buttons[i]);
buttons[i].addActionListener(this);
}
mainWindow.getContentPane().add(board,BorderLayout.CENTER); //Finish game pane init
}
public void actionPerformed(ActionEvent e){
if (e.getSource() instanceof JButton){
JButton j = (JButton)e.getSource();
j.setForeground(tictac2.blue ? Color.BLUE:Color.RED);
j.setText(tictac2.blue ? "X" : "O");
j.setEnabled(false);
tictac2.blue = !tictac2.blue;
}
else if (e.getSource() instanceof JMenuItem){
JMenuItem j = (JMenuItem) e.getSource();
if (j.getText().equals("Quit")) {
System.exit(0);
}
else if (j.getText().equals("New Game")) {
board.removeAll();
mainWindow.remove(board);
board = null;
for (int i = 0; i < 9; i++) {
buttons[i] = null;
}
newGameBoard();
tictac2.bWins = 0;
tictac2.rWins = 0;
tictac2.blue = true;
mainWindow.repaint(100);
}
}
}
public static void main(String[] args) {
new tictac2();
}
}
I am working on a tic tac toe program. In it I have 2 buttons. Whenever I hit new game, the newGameBoard function is supposed to run and make a new board. However, the screen just goes blank! I can't figure it out and would appreciate help. Sorry if I am not posting in the correct format, I am new here.
Thanks so much!
Move mainWindow.setVisible(true) to the end of init(). You don't want to set the frame to visible until you've added everything to it. That way it will validate and layout its subcomponents.
Another solution is to manually call mainWindow.validate() at the end of init(). That's what you have to do if you add components to the frame after making it visible.
use paintAll() or validate() on mainWindow:
mainWindow.validate();
instead of :
mainWindow.repaint(100);
validate and paintAll() as described in API doc.
Your changed code looks like:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class TicTac2 implements ActionListener{
static boolean blue = true; //used to keep track of turns. if true, blue's turn, else, red's turn. Blue is x, red is o
static int bWins = 0, rWins = 0;
JFrame mainWindow;
JPanel board;
JButton[] buttons;
public TicTac2() {
init();
}
private void init() {
try { //Try to set the L&F to system
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e) {
e.toString();
System.out.println("Couln't change look and feel. Using default");
}
mainWindow = new JFrame("Tic Tac Toe!");
mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainWindow.setVisible(true);
mainWindow.setSize(800,600);
JMenuBar bar = new JMenuBar(); //Menu bar init
JMenu file = new JMenu("File");
JMenuItem newGame = new JMenuItem("New Game"), quitItem = new JMenuItem("Quit");
file.add(newGame);
file.addSeparator();
file.add(quitItem);
bar.add(file);
mainWindow.getContentPane().add(bar, BorderLayout.NORTH); //Menu bar done
newGameBoard(); //New Game Board
JPanel infoPane = new JPanel();
infoPane.setLayout(new GridLayout(1,3));
JLabel turn = new JLabel("Blue Player's Turn"), spacer = new JLabel(""), score = new JLabel("Blue: 0, Red: 0");
infoPane.add(turn);
infoPane.add(spacer);
infoPane.add(score);
mainWindow.getContentPane().add(infoPane,BorderLayout.SOUTH);
newGame.addActionListener(this); //Add action listeners
quitItem.addActionListener(this);
}
private void newGameBoard() {
board = new JPanel(); //Game Pane init
board.setLayout(new GridLayout(3,3));
buttons = new JButton[9];
for (int i = 0; i <9; i++){
buttons[i] = new JButton("");
buttons[i].setOpaque(true);
buttons[i].setFont(new Font("sansserif", Font.BOLD, 90));
board.add(buttons[i]);
buttons[i].addActionListener(this);
}
mainWindow.getContentPane().add(board,BorderLayout.CENTER); //Finish game pane init
}
public void actionPerformed(ActionEvent e){
if (e.getSource() instanceof JButton){
JButton j = (JButton)e.getSource();
j.setForeground(TicTac2.blue ? Color.BLUE:Color.RED);
j.setText(TicTac2.blue ? "X" : "O");
j.setEnabled(false);
TicTac2.blue = !TicTac2.blue;
}
else if (e.getSource() instanceof JMenuItem){
JMenuItem j = (JMenuItem) e.getSource();
if (j.getText().equals("Quit")) {
System.exit(0);
}
else if (j.getText().equals("New Game")) {
board.removeAll();
mainWindow.remove(board);
board = null;
for (int i = 0; i < 9; i++) {
buttons[i] = null;
}
newGameBoard();
TicTac2.bWins = 0;
TicTac2.rWins = 0;
TicTac2.blue = true;
mainWindow.validate();
//mainWindow.repaint();
}
}
}
public static void main(String[] args) {
new TicTac2();
}
}