1. Computing

Label Overview


The Label Class


The Label class is used to create a non-editable text control. It can be used to display a String, or a String with an accompanying image which normally explain the purpose of another control on a graphical user interface. The text contained in a Label can be wrapped to fit a specific space or have visual effects applied to it (e.g., rotated, zoom).

Import Statement

import javafx.scene.control.Label;


The Label class has three constructors depending on whether you want to create a Label object with a String, an image or both:

  • To create an empty Label object:
    Label lbl = new Label();
  • To create a Label object with a String:
  • Label lbl = new Label("a String");
  • To create a Label object with a String and Image:
    //Use the javafx.scene.image.Image class to create an image 
    //object to reference the image for the Label.
    //This will actually be added to the Label as a Node - the ImageView
    //class takes care of this.
    Image image = new Image(getClass().getResourceAsStream("labelimage.jpg"));
    Label lbl = new Label("a String", new ImageView(image));

Useful Methods

If you create an empty Label you can set the text using the setText method:

lbl.setText("Another String");

Similarly, if you want to add an image to an existing Label object use the setGraphic method:

Image image = new Image("labelimage.jpg");
lbl.setGraphic(new ImageView(image));

There are corresponding methods getText and getGraphic which will return the String and Node used for the text and image of the Label:

String lblString = lbl.getText();
Node lblNode = lbl.getGraphic();

The color of the text of a Label can been changed easily using the setTextFill method:

//A color is represented by the javafx.scene.paint.Paint class. 
//It takes a String representation using the javafx.scene.paint.Color class. 
//This can be through a constant value (e.g., Color.BLUE, Color. GREEN

To wrap the text of a Label use the setWrapText method. This is useful if the Label must be confined into a small area lengthwise:


To change the font of the text use the setFont method. For example, to change the font to Arial with a size of 25:


Usage Tips

A Label can be set up to send the focus to another control by using a mnemonic. This can be a nice shortcut for the user to quickly get to the control the label is defining. In order to set up the shortcut the setMnemonicParsing and setLabelFor methods are used:

//First you have to set up the keyboard shortcut. This is done by adding an underscore 
//in front the desired letter:
lbl.setText("_Another String");

//Next, turn on the mnemonic parsing for the control

//Finally, set the control the shortcut is for
TextField txtFld = new TextField();

In this way on a Windows machine pressing ALT-A will send the focus to the TextField control.

To find out about other JavaFX controls have a look at JavaFX User Interface Controls.

©2014 About.com. All rights reserved.