Return to Course Content Home

JLabels

Optional Reading

We will be using the Creating a GUI with JFC/Swing tutorial from Sun as a Reference source. You are not required to read the entire tutorial, I suggest you skim through it though to use a a supplement to what I give you here.

JLabels

If JPanel is a general purpose container for components, JLabel is the general purpose container for text and graphics.

The name JLabel carries with it the idea of a text label, but what is sometimes overlooked is that a JLabel holds text and/or an icon. Since an icon can be any size, you can use JLabel as a container for images just as easily as holding text.

Most current version of Java do more than just support regular text. If you place HTML strings as the content for the String argument for JLabels, the HTML will be rendered as HTML and not just plain text! (Actually it needs to be XHTML, you need to have <html> (lower case) for it to work). You can't embed images in your HTML, and a JLabel rendering HTML will ignore any setFont() methods used on it as well.

There are several constructors, but they are variations of setting text, icons and content alignment values.

JLabel()
JLabel(String text)
JLabel(String text, int horizontalAlignment)
JLabel(String text, Icon icon, int horizontalAlignment)
JLabel(Icon icon)
JLabel(Icon icon, int horizontalAlignment)

One idiosyncrasy of JLabels is that be default their backgrounds are transparent. Normally that is good, but if you really want to set the background color of a JLabel, you need to call the setOpaque(true) method on the JLabel.

If you look closer, you'll see that the Icon argument type above is actually an Interface. There is an ImageIcon class that you can use to load graphic images and then use them in the JLabel.

Icon icon = new IconImage(getClass().getResource("duke.gif");
JLabel label = new JLabel("duke", icon);

This would load in the duke.gif image into the icon object, and then the JLabel would display it.

The other issue is that the Icon interface only has three methods:

public interface Icon {
   public void paintIcon (Component comp, Graphics g, int x, int y);
   public int getIconWidth();
   public int getIconHeight();
 }

You can use your new skill as a Java2D expert to use these methods to "paint" your own icons from the screen. This is actually how Java "paints" all of the icons it uses. They aren't gif's or png's, the icons are actually paint methods in internal classes!

Download and open the Netbeans project jlabel.zip. If you run the application, the following window will appear:

JLabels

There are three JLabels in the above window. The first is a right aligned, text only label, with the words "Text Only", the second is a center aligned JLabel with the Duke image and the text "Duke", the last image uses HTML. Note that with HTML we can get multiple lines of text in a single JLabel.