/* * File: TicTacToe.java * -------------------- * This application uses TableLayout to create a 3x3 array * of JButtons. Clicking on an empty button changes its label * to an X or an O, as appropriate. */ import acm.gui.*; import acm.program.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class TicTacToe extends Program implements ItemListener { /** Set the program dimensions */ public static final int APPLICATION_WIDTH = 225; public static final int APPLICATION_HEIGHT = 225; /** Font to use for the buttons */ public static final Font BUTTON_FONT = new Font("SansSerif", Font.BOLD, 36); /** Initialize the application */ public void init() { weightCheckBox = new JCheckBox("Use weights"); add(weightCheckBox, SOUTH); weightCheckBox.addItemListener(this); setLayout(new TableLayout(3, 3)); for (int i = 0; i < 9; i++) { JButton button = new JButton(""); button.setFont(BUTTON_FONT); add(button, "width=60 height=60"); } turn = 'X'; addActionListeners(); } /** Sets whether the buttons use weights or constant widths */ public void setWeightFlag(boolean flag) { String constraints = "fill=BOTH"; if (flag) { constraints += " weighty=1 weightx=1"; } else { constraints += " width=60 height=60"; } TableLayout layout = (TableLayout) getLayout(); Container centerPanel = getRegionPanel(CENTER); int nc = centerPanel.getComponentCount(); for (int i = 0; i < nc; i++) { Component comp = centerPanel.getComponent(i); layout.setConstraints(comp, constraints); } validate(); } /** Respond to action events by changing the button label */ public void actionPerformed(ActionEvent e) { JButton button = (JButton) e.getSource(); if (button.getText().equals("")) { switch (turn) { case 'X': button.setText("X"); turn = 'O'; break; case 'O': button.setText("O"); turn = 'X'; break; } } } /** Respond to item events by resetting the constraint options */ public void itemStateChanged(ItemEvent e) { JCheckBox checkBox = (JCheckBox) e.getSource(); setWeightFlag(checkBox.isSelected()); } /* Private instance variables */ private char turn; private JCheckBox weightCheckBox; /* Standard Java entry point */ /* This method can be eliminated in most Java environments */ public static void main(String[] args) { new TicTacToe().start(args); } }