Java: Styling a Swing JLabel

A quick post here really, as I found it difficult to find this information all in one place, anywhere else.

I’m not usually a Java programmer, but it is used as part of some of our courses and assignments at Uni. We’ve recently gone into setting up GUIs and something that I wanted to do was style my read-only text, or JLabels. Searching brought me to many incomplete answers, or answers on forums like “Font() is your friend”, hinting to look into the documentation.

However the documentation for Font() is incredibly broad and not the smallest of pages, so for this specific case, I think it would be more useful to have all the information on the page. There are also other types of styling which Font() does not cover…

Using Font() to style your JLabel

It is assumed that you understand what a JLabel is, how to create an instance of one and what to do with one after you’ve created it and styled it. But just for completeness to start with, we’ll add in a JLabel creation. Styling the actual text is done by creating a Font object with the necessary parameters specified. First we’ll style a label to the default styling given to a JLabel.

JLabel label = new JLabel("Hello There!");
label.setFont(new Font("Sans Serif", Font.PLAIN, 12));

Testing this won’t really show much visually, as it will look like this, regardless of whether you specify the style. But it’s good to know what you’re changing the styling from, especially if you ever want to return a label to it’s normal style. But now let’s try something a bit different.

JLabel label = new JLabel("Hello There!");
label.setFont(new Font("Serif", Font.BOLD, 28));

This will be visibly different, changing the font to a Serif font, bolding it and increasing the font size to 28. To clarify, to create a new Font() object you need to specify the parameters like so:

new Font(String [Font Name], int [Font Style], int [Font Size]);

Font Name – As with CSS, there are safer fonts than others to use, the documentation for Font() states:

This can be a font face name or a font family name, and may represent either a logical font or a physical font found in this GraphicsEnvironment. The family names for logical fonts are: Dialog, DialogInput, Monospaced, Serif, or SansSerif. Pre-defined String constants exist for all of these names, for example, DIALOG.

So there are the safest, basic fonts, which can all be accessed using a constant such as Font.SERIF and there are physical fonts found in the GraphicsEnvironment. On a closer look, it seems that, in simple terms anyway, the GraphicsEnvironment is an interface between the Java Virtual Machine and the host operating system. So any font you have installed should be accessible. However, as with CSS once again, you should only use fonts which most/all computers have by default, for portability reasons. For more information on “web-safe” fonts. See the link in further reading.

It seems that you may also be able to specify a Font Style within this string, though I feel personally, it seems like a route to confusion.

Font Style – Whether or not there are more constants within Font() that can be used for this parameter, the documentation states there are three basic styles, Font.PLAIN, Font.BOLD and Font.ITALIC. To achieve a bold, italic style. You may use both constants like so.

// Other parameters omitted.
new Font(..., Font.BOLD|Font.ITALIC, ...);

Font Size – Self explanatory really, but this size is in pt and is just a number, no need for anything else.

Colour? Alignment?

This is where Font() can no longer help, both these styles are done with other methods.

Colour

To colour the text, there is an aptly named method for this.

label.setForeground(Color.green);

As can be seen, Color() is brought in to make selecting a colour easier, however, if you look into the Color() class, you can find out how to specify a custom colour if you needed. See “Further Reading” for the documentation for this class.

NB: The Colour() class is in the java.awt group, so if you’re importing java.awt.* then you should be fine. If not, then you will need to import this separately.

To set the background colour, a little more trickery is required.

//Slightly more complete code to put code into context.
label = new JLabel("Hello There!");
label.setForeground(Color.green);
JPanel labelBG = new JPanel();
labelBG.setBackground(Color.black);
labelBG.add(title);

Because the background of a JLabel is transparent, using label.setBackground(Color.black); wouldn’t change anything visibly. Instead, using a JPanel to contain just the JLabel enables us to give the background a colour.

Alignment

Alignment is again set with another set of methods, and what’s worse is that there are exceptions. In a normal situation, with a default layout set. You can centre the text in a JLabel like so…

label.setHorizontalAlignment( SwingConstants.CENTER );

There is also a setVerticalAlignment(); method which works in a similar way, however, if you try either of these methods with an element (it’s not just JLabels that these methods exist in) within a BoxLayout, there will be no visible effect. For this, there is another set of methods.

label.setAlignmentX(0.5f);

This code would centre the element, while replacing 0.5f with 0.0f would align the element to the right and 1.0f would align the element to the left. There is also a setAlignmentY(); which will work in a similar way, these differing methods of alignment have been brought up as a bug in the past, but it is explained that they do different things and the layouts work in different ways.

I made a quick method which would centre both JLabels in BoxLayout or otherwise.

/**
 * Centre the alignment of a swing JLabel.
 *
 * @param swingLabel The JLabel to be centered.
 * @return The JLabel that has been centered.
 */
 private JLabel centreLabel(JLabel swingLabel)
 {
 swingLabel.setHorizontalAlignment( SwingConstants.CENTER );
 swingLabel.setAlignmentX(0.5f);
 return swingLabel;
 }

Hopefully that should’ve demystified many of the issues with styling swing elements. If not, see if the links in further reading help out any more.

Further Reading

Quick Font & Colour Info
List of Web Safe Fonts
Font() Java Documentation
Color() Java Documentation
Information on GraphicEnvironment

Advertisements

Published by

Andrew Bridge

A student web developer with a keen interest in bringing function and form together as one to create a powerful, beautiful experience for users.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s