Coding 2: Creating the Game Window

We will be using Java's Swing Library to create our Game Window.

If you would like to know more about Swing and Graphical User Interfaces, read more about them in Lesson 7.

Carrying on from Coding 1...

Open up the Game class and you should see an empty class:

public class Game {

}

First, we need to inherit Swing Library's JFrame class in order to make our Game class represent our Game Window. If you are unfamiliar with the concepts of inheritence, I recommend you to read Lesson 4.

So how do we do this?
Simply extend the JFrame class:

public class Game extends JFrame{

}

Eclipse should tell you that JFrame cannot be resolved to a type. This is because we haven't imported the library to our class, so we can do this now by adding the following code to the top:

import javax.swing.JFrame;

The next thing we need in this class is a main function, which is the first function that is executed when the program starts. So let's go ahead and make a main method:

public static void main(String[] args) {

}

Before we write the code for the main method, let's first create a constructor for the game class like this:

public Game() {

}

In this constructor, we will initialise our JFrame attributes which will determine the characteristics of our game window.

public Game() {
    setTitle("Whack A Mole");
    setResizable(false);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 608, 720);
}

setTitle("Whack A Mole") - sets the title of the window
setResizable(false) - forces the window to be a fixed size
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) - configures the window such that when the user clicks the 'X' button on the top-right corner of the window, the program will exit
setBounds(100, 100, 608, 720) - sets the x, y position of the window and the width and height of the window (x, y, width, height)

Now that we have a constructor for the Game class, let's go ahead and initialise a Game object in the main function.

public static void main(String[] args) {
    Game frame = new Game();
    frame.setVisible(true);
}

Game frame = new Game() - instantiates a Game object called 'frame'
frame.setVisible(true) - makes the frame (Game object) visible on the screen

Now it's time to test our code we wrote so far...

Click on the green play button or hit Ctrl+F11

You should see an empty window on your screen with the title: WhackAMole

If you can't get this to show, do not worry, the full code for each coding lesson will be posted at the bottom of the page.

Coding 2: Source Code

import javax.swing.JFrame;

public class Game extends JFrame{
    public Game() {
        setTitle("Whack A Mole");
        setResizable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 608, 720);
    }

    public static void main(String[] args) {
        Game frame = new Game();
        frame.setVisible(true);
    }
}