By Tony Bevis on Wednesday, 18 October 2023
Category: Java

Java programming course: 14.2 JLabel

Previous lesson: 14.2 How to use JFrame to provide a desktop window

Course contents

JLabel

The JLabel class will show a read-only piece of text:

If you run the frame, you should see the following:

By default, the text is left aligned, but you can optionally supply a second argument to the constructor to specify right or centre alignment:

If you need to change the text that appears on the label you can invoke the setText() method:

There is also a getText() method which returns the text to be displayed as a String.

If you want to show the label using a different font you can instantiate and assign a suitable Font object:

The Font constructor accepts three argument values:


If you want the text to be shown in a particular colour you can assign a suitable Color object either through one of its colour constants or a colour combination you specify:

If you use the red, green, blue combination constructor then each value must be between 0 and 255 to indicate the amount of that colour that should be used. This allows you to obtain fine degrees of shading.

Next lesson: 14.3 JTextField

Related Posts

Leave Comments