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.

This figure is composed of nine square buttons arranged in a square formation. Each button has either no label, the label X or the label O.

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

Constructor

Takes a single String argument used to set the title of the frame.

Instructions

  1. 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.
  2. Add a new Java class called LayoutDemo to the project and write code to meet the specification above.
  3. 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.
  4. 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.
  5. 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

  1. 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.

  2. 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.