teaching machines

CS 245 Lab 2 – GUI Programming

September 11, 2013 by . Filed under cs245, fall 2013, labs.

First, if you have checkpoints left over from last lab, get them inspected during the first 15 minutes of this lab.

Don’t forget to work in pairs! Where possible, please work with someone that you did not work with last week. The exchange of new ideas and perspectives is not an opportunity you want to rob yourself of.


In this lab, you will dive into using Java’s Swing library to create graphical applications. You will create a tic-tac-toe game comprised of buttons, a label, and a window. The first checkpoint focuses on presentation, the second on implementing the game logic.

Checkpoint 1

With A at the computer, pop open a JFrame that shows a JFrame with a 3×3 grid of JButtons and a JLabel status message, following these constraints:

You’ll hit a slight hiccup when you discover that each region of the border layout can only hold one widget. You can overcome this hiccup by creating a JPanel (a generic widget that holds other widgets), adding the buttons to it, and putting the JPanel in the center of the JFrame.

To layout the buttons in a 3×3 grid, give your JPanel a GridLayout.

The status message should initially say something like, “O’s turn” or “X’s turn.”

Checkpoint 2

Add event handlers to your buttons. When player O presses a button, change the button’s text label to O and deactivate it. Likewise for X. Update the status message to prompt the next player to make a move.

When a player wins, say so in the status message and deactivate all remaining buttons.

When the players come to a draw, say so in the status message.