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:
- 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. - Add code to
main()
to create a newGuessMyColor
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.
- At the beginning of the constructor, create a
JLabel
object calledtitleLabel
, with no parameters. - Create a new font called
titleFont
this is in the Serif family, bold, and size32
. - Set the font of
titleLabel
totitleFont
using JLabel’ssetFont()
method. - Set the horizontal alignment of titleLabel to center-aligned using JLabel’s
setHorizontalAlignment()
method and JLabel’sCENTER
variable. - Set the text of titleLabel to "Guess My Color” using JLabel’s
setText()
method. - Add
titleLabel
to the window using JFrame’sadd()
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.
- Create a private method called
initGUI()
. It should take no parameters and return nothing. - Move six lines of code in the constructor that created the
titleLabel
and add it to theinitGUI()
method. - 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?
- In
initGUI()
, create aJLabel
object calledanotherLabel
. - Set the text of
anotherLabel
to “2nd Label” usingJLabel
'ssetText()
method. - Add
anotherLabel
to the window usingJLabel
'sadd()
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.
- Change the code as shown using
JFrame
'sadd()
method with a second parameter value. We’ll also need to use BorderLayout’sPAGE_START
andCENTER
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 isBorderLayout
. - 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
. TheBorderLayout
's location variables arePAGE_START
,PAGE_END
,LINE_START
,LINE_END
, andCENTER
. These variables are static variables, so we will useBorderLayout.
with these variables. For example, to add aJLabel
callednameLabel
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
andLINE_END
are relative locations. If the component’s orientation isLEFT_TO_RIGHT
,LINE_START
refers to the left area andLINE_END
refers to the right area. If the component’s orientation isRIGHT_TO_LEFT
,LINE_START
refers to the right area andLINE_END
refers to the left area. The component’s default orientation isLEFT_TO_RIGHT
. To change a component’s orientation, we will use the component’ssetComponentOriention()
method.BorderLayout
's five areas may also be referred to asNORTH
,SOUTH
,EAST
,WEST
, andCENTER
.NORTH
is the same as thePAGE_START
variable.SOUTH
is the same as thePAGE_END
variable.EAST
is always to the right of theCENTER
. AndWEST
is always to the left of theCENTER
. However, Java standards recommend that we usePAGE_START
,PAGE_END
,LINE_START
, andLINE_END
, so that our program can adapt more easily to languages that have different orientations.