Lab 16: GUI Part I

The goal of this lab is to practice using Java's GUI capabilities to write programs that use windows and buttons.

You may find the notes from the last couple of class meetings useful (about collections and Swing components). Recall that class notes and examples are in directories under /cslab/class/csci235/in-class, organized by date. So you might want to open another terminal window and cd there. The command to view a PDF file is evince.

1. Introduction

A Fifteen Puzzle (or, more generally, an N-puzzle) consists in a grid of square, same-sized tiles, with all but one of the grid positions filled. The object of the game is to rearrange the tiles by sliding the tiles one at a time until a certain configuration is reached (for example, starting from a random configuration until the numbers are in order).

In this lab, you will write a program that simulates a Fifteen Puzzle

2. Set-up

Clone the repository from the class public directory:

hg clone /cslab/class/csci235/lab16
cd lab16

Open FifteenPuzzle.java in xemacs and read through it. Notice that it basically adds sixteen buttons to the window. Compile and run, and notice that the buttons are put right on top of each other, and all the buttons are blank.

3. Adjusting the window

Based on what we've seen in class, play around with the size, location, and layout management until it looks reasonably nice. Don't bother putting text on the buttons yet.

4. Making the puzzle work

Each button stands for a tile or block in the puzzle. 15 of them will have numbers, and the 16th will be blank. We won't actually move the buttons around; instead, we will change the numbers on the buttons to give the appearance of moving tiles.

When a button is clicked, the following should happen:

Each button needs to have an action listener to perform this. Uncomment the relevant sections in FifteenPuzzle.java. We are using an action listener class called PuzzlePiece. The skeleton of this class is given to you. Finish it by filling in the bodies for the following methods (read through all this before starting, though):

Hint: Notice again that when a button is clicked, its action listener must communicate with the action listeners on the neighboring buttons---first, to determine if one of the neighbors is blank; second, to make any necessary changes. How can you do this? You may want to write a few extra methods in the class PuzzlePiece.

5. Turn in

Turn in your .java source files with a command

/cslab/class/csci235/bin/handin lab16 PuzzlePiece.java FifteenPuzzle.java

Be sure to include all of your files on a single command.


Thomas VanDrunen, Cary Gray
Last modified: Fri Nov 18 11:04:29 CST 2011