Game Description and Initial Setup

Understand the description of the game and do the initial setup for it, including adding labels and separating the GUI.

Description

The Guess My Color game shows a sample color, initially black, and target color. The objective of the game is to slowly add or remove small amounts of red, green, and blue from the sample to try to match the target color.

Even if you do not see color differences well, consider writing this game anyway. Guess My Color is a good introduction to how to work with colors, panels, layouts, buttons, and message dialogs.

A layout arranges the components in a container. The default arrangement of components in a JFrame is the BorderLayout.

Initial setup for GuessMyColor

We have provided you with a Java project, required class, and necessary package. Our package will be called guessmycolor. We have also provided the libraries required for this project.

To start writing the Guess My Color program:

  1. Add a GuessMyColor constructor with no parameters. Set the window’s title to “Guess My Color”, disable resizing, pack the window, center the window, make the window visible, and set the window to exit when closed.
  2. Add code to main() to create a new GuessMyColor object.
...
public class GuessMyColor extends JFrame {
    public GuessMyColor(){ 
        setTitle(_______________); 
        setResizable(_________);    
        ___________(); 
        setLocationRelativeTo(____); 
        setVisible(_________); 
        setDefaultCloseOperation(______________);
    }
    public static void main(String[] args) {
        new ____________;
    }
}
...

Please click the Show Solution button below, to see the complete code.

Use what you have learned so far about labels, fonts, and text alignment to add a title label to the window.

  1. At the beginning of the constructor, create a JLabel object called titleLabel, with no parameters.
  2. Create a new font called titleFont this is in the Serif family, bold, and size 32.
  3. Set the font of titleLabel to titleFont using JLabel’s setFont() method.
  4. Set the horizontal alignment of titleLabel to center-aligned using JLabel’s setHorizontalAlignment() method and JLabel’s CENTER variable.
  5. Set the text of titleLabel to "Guess My Color” using JLabel’s setText() method.
  6. Add titleLabel to the window using JFrame’s add() method.
...
public GuessMyColor() {
   JLabel titleLabel = new ______________;
   Font titleFont = new Font(Font.______,Font._______, ____); 
   titleLabel.setFont(____________); 
   titleLabel.setHorizontalAlignment(_______________); 
   titleLabel.setText(____________);
   add(_______________);
   setTitle("Guess My Color");
...

Please click the Show Solution button below, to see the complete code.

After following these steps in the code playground given at the bottom of the lesson, Click on the run button. The window will display a large, bold title: “Guess My Color”.

Separate the graphical user interface

Creating and arranging the components, also called the graphical user interface (GUI), will take many lines of code. Move the GUI to a separate method to better organize the code.

  1. Create a private method called initGUI(). It should take no parameters and return nothing.
  2. Move six lines of code in the constructor that created the titleLabel and add it to the initGUI() method.
  3. Call initGUI() at the start of the constructor.
...
public GuessMyColor() {
   ___________();
   setTitle("Guess My Color"); 
   setResizable(false);
   pack();
   setVisible(true); 
   setDefaultCloseOperation(EXIT_ON_CLOSE);
   }
_________ ______ initGUI(______) {
   JLabel titleLabel = new JLabel();
   Font titleFont = new Font(Font.SERIF, Font.BOLD, 32);    
   titleLabel.setFont(titleFont); 
   titleLabel.setHorizontalAlignment(JLabel.CENTER); 
   titleLabel.setText("Guess My Color"); 
   add(titleLabel);
}
...

Please click the Show Solution button below, to see the complete code.

After making the above changes in the code, the program will run the same as it did before.

Add another label

So far, your windows have always had only one label. What happens if you add a second label?

  1. In initGUI(), create a JLabel object called anotherLabel.
  2. Set the text of anotherLabel to “2nd Label” using JLabel's setText() method.
  3. Add anotherLabel to the window using JLabel's add() method.
...
private void initGUI() {
    ...
    titleLabel.setText("Guess My Color");
    add(titleLabel);
    JLabel anotherLabel = new ____________;
    anotherLabel.setText(_________);
    add(_______________);
}
...

Please click the Show Solution button below, to see the complete code.

When you follow the above steps, on clicking the run button, the program will display “2nd Label” but not “Guess My Color”. Where did “Guess My Color” go? It was replaced by the second label.

Change component placement

If you add more than one component to a JFrame class, set a location for each component.

  1. Change the code as shown using JFrame's add() method with a second parameter value. We’ll also need to use BorderLayout’s PAGE_START and CENTER variables.
    ...
    JLabel titleLabel = new JLabel();
    Font titleFont = new Font(Font.SERIF, Font.BOLD, 32);
    titleLabel.setFont(titleFont);
    titleLabel.setHorizontalAlignment(JLabel.CENTER);
    titleLabel.setText("Guess My Color");
    add(titleLabel, BorderLayout.PAGE_START);
    JLabel anotherLabel = new JLabel();
    anotherLabel.setText("2nd label");
    add(anotherLabel, BorderLayout.CENTER);
}
...

On running the code after making the above changes, both labels will be displayed.

Implement and test the concepts you learned in this lesson in the code editor below. However, if you try to execute without adding any changes, you will see a blank screen.

package guessmycolor;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class GuessMyColor extends JFrame {

    // add code here

    public static void main(String[] args) {
         EventQueue.invokeLater(new Runnable() {
            public void run() {
                new GuessMyColor();
            }    
        });    
    }

}

Key points

  • A JFrame window uses a border layout to arrange components in a window. The border layout’s class name is BorderLayout.
  • Each of BorderLayout's five areas can hold only one component.
    • The top area is referred to as the “page start”.
    • The bottom area is referred to as the “page end”.
    • The left area is referred to as the “line start”.
    • The right area is referred to as the “line end”.
    • The large middle area is referred to as the “center”.
  • We must always set a location whenever we add a component to a BorderLayout. The BorderLayout's location variables are PAGE_START, PAGE_END, LINE_START, LINE_END, and CENTER. These variables are static variables, so we will use BorderLayout. with these variables. For example, to add a JLabel called nameLabel to the top of a window, use:
add(nameLabel, BorderLayout.PAGE_START);
  • If a component is added to a BorderLayout without setting a location, the program puts the component in the center area.
  • If a second component is located in an area of a BorderLayout that already has a component, the second component will replace the first component.
  • Components added to the areas of a BorderLayout will be stretched to fill the window:
    • Components added to the top and bottom areas will be stretched as wide as the window.
    • Components added to the side areas will be stretched in height, and made as tall as the middle area.
    • Components added to the middle area will be stretched in height to the same height as the side areas, and stretched in width to make the total side and middle areas as wide as the window.
    • We will see these five areas as colored rectangles in the next lesson.
  • If nothing is added to an area of a BorderLayout, that area will not be included in the window.
  • LINE_START and LINE_END are relative locations. If the component’s orientation is LEFT_TO_RIGHT, LINE_START refers to the left area and LINE_END refers to the right area. If the component’s orientation is RIGHT_TO_LEFT, LINE_START refers to the right area and LINE_END refers to the left area. The component’s default orientation is LEFT_TO_RIGHT. To change a component’s orientation, we will use the component’s setComponentOriention() method.
  • BorderLayout's five areas may also be referred to as NORTH, SOUTH, EAST, WEST, and CENTER. NORTH is the same as the PAGE_START variable. SOUTH is the same as the PAGE_END variable. EAST is always to the right of the CENTER. And WEST is always to the left of the CENTER. However, Java standards recommend that we use PAGE_START, PAGE_END, LINE_START, and LINE_END, so that our program can adapt more easily to languages that have different orientations.