Activity 6.2 - Constructing a frame using GridLayout
Topic
In this activity we use a GridLayout to display buttons in a 3 x 3
arrangement.
Task
The task is to produce a frame, which has a JPanel on it. On the JPanel nine
buttons are to appear, so that it looks like a partially complete game of
noughts-and-crosses.

The size of frame should be 200 x 200, its title "Tic-tac-toe" and its
location (200, 200).
The frame is to be an object of class LayoutDemo, which extends JFrame and
whose outline is as follows:
Imports
AWT and Swing.
Instance variables
- Nine variables of type JButton to represent the buttons.
- One variable of type JPanel.
Constructor
Takes a single String argument used to set the title of the frame.
- Sets the title.
- Sets the size to 200 x 200.
- Positions the top left-hand corner of the frame at screen location (200,
200).
- Creates nine JButton instances with text either "O", "X" or " " and assigns
them to the corresponding instance variables.
- Creates an instance of JPanel and assigns it to the corresponding variable.
- Sets the layout of the JPanel to a 3 x 3 grid layout.
- Adds the nine buttons to the panel.
- Gets the content pane of the JFrame.
- Adds the panel to the content pane.
Instructions
- Following the same procedure as in Activity 6.1, create a new project in the Unit 6 folder, but this time called MyEx6_2. In the New Java Application wizard name the Main Class myex6_2.LayoutDemoTest.
- Add a new Java class called LayoutDemo to the project and write code to meet the
specification above.
- Complete the main class LayoutDemoTest so that it creates a test instance of LayoutDemo with the title "Tic-tac-toe" and makes the new frame visible. Run the project to test your code. Our sample solution appears in the Solution file.
- As an experiment, go back and comment out the line of code in which
you set the grid layout. The layout will revert to the default for a JPanel, which
is FlowLayout. Re-run the program to see the effect of this change.
- Now restore the grid layout but use a four-argument constructor:
GridLayout(int rows, int cols, int hgap, int vgap)
Set hgap and vgap to 10 and run the program to see what difference this
makes.
Notes
In this example, it would have been possible to omit the JPanel and add
the buttons directly to the content pane. However using a panel is better
programming practice, and panels will become essential in the exercises which
follow, so we decided to use one here.
You will probably have noticed that closing a JFrame does not
automatically stop the program, which is rather inconvenient. Although how it
works is not covered until the next unit, you may like to add the following line
of code to your program, immediately following the statements that set the
title, size and location.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
The program should now halt when the window is closed.