In this tutorial

You will learn how to...
  • How to create a JLabel.
  • How to colour a JLabel.
  • How to align a JLabel horizontally.

JLabels

JLabels are used in Swing to display a line or so of text in a way that cannot be directly edited by the user. This makes them very useful for naming items on the GUI, pointing things out or indicating progress through a process.

To demonstrate a JLabel, we will start from the answer from Exercise 3 in the last tutorial.
This time, we are going to extend the height of the JFrame a little to fit everything in. We will also create a 5th JPanel to put the labels on.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import javax.swing.*;
import java.awt.Color;

public class LabelExample{

    public JPanel createContentPane (){

        // We create a bottom JPanel to place everything on.
        JPanel totalGUI = new JPanel();
        totalGUI.setLayout(null);

        // Creation of a Panel to contain the JLabels
        JPanel textPanel = new JPanel();
        textPanel.setLayout(null);
        textPanel.setLocation(10, 0);
        textPanel.setSize(260, 30);
        totalGUI.add(textPanel);

        // First JLabel, outputs "Red".
        // Added to the 'textPanel' JPanel
        JLabel redLabel = new JLabel("Red");
        redLabel.setLocation(0, 0);
        redLabel.setSize(50, 40);
        redLabel.setHorizontalAlignment(0);
        textPanel.add(redLabel);

        // Second JLabel, outputs "Yellow"
        JLabel yellowLabel = new JLabel("Yellow");
        yellowLabel.setLocation(70, 0);
        yellowLabel.setSize(50, 40);
        yellowLabel.setHorizontalAlignment(0);
        textPanel.add(yellowLabel);

        JLabel greenLabel = new JLabel("Green");
        greenLabel.setLocation(140, 0);
        greenLabel.setSize(50, 40);
        greenLabel.setHorizontalAlignment(0);
        textPanel.add(greenLabel);

        JLabel blueLabel = new JLabel("Blue");
        blueLabel.setLocation(210, 0);
        blueLabel.setSize(50, 40);
        blueLabel.setHorizontalAlignment(0);
        textPanel.add(blueLabel);

        // Creates a panel to hold the following panels.
        JPanel panelForPanels = new JPanel();
        panelForPanels.setLayout(null);
        panelForPanels.setLocation(10, 40);
        panelForPanels.setSize(260, 50);
        totalGUI.add(panelForPanels);

        JPanel redPanel = new JPanel();
        redPanel.setBackground(Color.red);
        redPanel.setLocation(0, 0);
        redPanel.setSize(50, 50);
        panelForPanels.add(redPanel);

        JPanel yellowPanel = new JPanel();
        yellowPanel.setBackground(Color.yellow);
        yellowPanel.setLocation(70, 0);
        yellowPanel.setSize(50, 50);
        panelForPanels.add(yellowPanel);

        JPanel greenPanel = new JPanel();
        greenPanel.setBackground(Color.green);
        greenPanel.setLocation(140, 0);
        greenPanel.setSize(50, 50);
        panelForPanels.add(greenPanel);

        JPanel bluePanel = new JPanel();
        bluePanel.setBackground(Color.blue);
        bluePanel.setLocation(210, 0);
        bluePanel.setSize(50, 50);
        panelForPanels.add(bluePanel);
        
        totalGUI.setOpaque(true);
        return totalGUI;
    }

    private static void createAndShowGUI() {

        JFrame.setDefaultLookAndFeelDecorated(true);
        JFrame frame = new JFrame("[=] JLabel Fables [=]");

        //Create and set up the content pane.
        LabelExample demo = new LabelExample();
        frame.setContentPane(demo.createContentPane());

        // The other bits and pieces that make our program a bit more stable.
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(290, 130);
        frame.setVisible(true);

    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}
The program looks like this now when it is run.

Picture of Labels

Now there seems to be quite a lot of code, but most of it is very simple. Before we go into the JLabels, we shall quickly refresh our knowledge of the JPanel set-up from the previous tutorial.

The JPanel is created just as before. Because it is a JPanel within the ContentPane JPanel, we must now distinguish that the JPanel we want to edit is the textPanel. So, we prefix all our commands with "textPanel.". We add the JPanel to the bottom JPanel using totalGUI.add(); just like we always do.
13
14
15
16
17
        JPanel textPanel = new JPanel();
        textPanel.setLayout(null);
        textPanel.setLocation(10, 0);
        textPanel.setSize(260, 30);
        totalGUI.add(textPanel);
Now we create a JLabel to put in the JPanel. The String argument passed when the JLabel is created is the text to be displayed in the label.
21
        JLabel redLabel = new JLabel("Red");
We set the size as before. The location is set, but this is the location within the textPanel NOT the totalGUI content pane. This means if the textPanel is moved at all, the JLabel will keep the same size and spacing within the JPanel.
22
23
        redLabel.setLocation(0, 0);
        redLabel.setSize(50, 40);
A command you have not seen before is the setHorizontalAlignment(). The text is aligned to the centre by using one of the constant field values. You can find them in the Java API, but for reference...
You can find more about setHorizontalAlignment by using the Sun API.
setHorizontalAlignment(int)
Constant Field Values

24
        redLabel.setHorizontalAlignment(0);
Finally, we add the JLabel to textPanel. We explicitly define the JPanel we are adding the JLabel to as textPanel. If we simply used totalGUI.add() as apposed to textPanel.add(), the JLabel we just created would be added to the ContentPane.
25
        textPanel.add(redLabel);
By completing this four times, we give each of the coloured JPanels we made in the last tutorial a title. It looks very nice.

Exercises

Exercise 1 - Colouring Labels

Using the setForeground(Color); command, colour...

Red title - Cyan
Yellow title - Magenta
Green title - Orange
Blue title - Pink

Exercise Hint
Exercise Example Code

Exercise 2 - Triffic Traffic Lights

In a JFrame, we would like you to model a set of traffic lights, with the name of each colour in the middle of it. The traffic light box will be a JPanel with a coloured JPanel of Red, Yellow and Green placed within the box (using the .add() command). A JLabel describing each colour will be placed within each coloured JPanel (using the .add() command.)

It should end up like this...

Traffic Lights

To make things easier, here are some tips.

Exercise Example Code

Questions

To make sure you have understood the tutorial, answer these quick questions on the JLabel.

Question 1. When instantiating a JLabel, what is the String argument for?

  • a) To pass the text to be displayed on the JLabel.
  • b) To pass the colour the text should be.
  • c) To set the horizontal alignment.

Question 2. What is the ConstantValue of CENTER in the setHorizontalAlignment() command?

  • a) 0
  • b) 1
  • c) 23

Question 3. Without being told specifically, how do you think we get the text from a JLabel?

  • a) .returnText();
  • b) givethetext();
  • c) .getText();




Now take the next step along the path of enlightenment - 4. JButtons

Back Top Next
Email Me
Code Style


Required Lessons

External Links

Created and Edited by Stuart Davidson
All Rights Reserved ©

Valid XHTML 1.0 Strict