Learn how to display fixed text or images with JLable component.
Labels display fixed text or images on a GUI as information to the user, for example, as a label in front of a a JTextField, etc.
You can have text (including HTML), an image, or both on a JLabel. A JLabel has a transparent background, so it will always match the container it is in.
Here we are discussing about the JLabel constructors.
Assume the following declarations.
String text; Icon image; int alignment; //
JLabel yourLabel = new JLabel(text); JLabel yourLabel = new JLabel(text, alignment); JLabel yourLabel = new JLabel(image); JLabel yourLabel = new JLabel(image, alignment); JLabel yourLabel = new JLabel(text, image, alignment);
Because there is usually no need to refer to a JLabel after it has been added to a container, it is common to combine creation and adding the JLabel in one statement. For example.
p.add(new JLabel("Enter your ID:", JLabel.RIGHT));
is the same as
JLabel idLabel = new JLabel("Enter your ID:", JLabel.RIGHT); . . . p.add(idLabel);
You may put HTML text in a JLabel. In this case the text should
<html> and end with
The most user-friendly interfaces are usually obtained by using the default appearance (font, color, background), but there are cases where you want to change these.
The font of a JLabel can be changed like this.
JLabel title = new JLabel("Want a Raise?", JLabel.CENTER); title.setFont(new Font("Serif", Font.BOLD, 48));
Use the setForeground method to set the text color.
JLabel title = new JLabel("Want a Raise?", JLabel.CENTER); title.setForeground(Color.white);
Because a JLabel's background is transparent, there is no effect from using the setBackground method. To make a new background, you need to create a JPanel with the appropriate color and put the label on that. For example
JLabel title = new JLabel("Want a Raise?"); title.setForeground(Color.white); JPanel titlePanel = new JPanel(); titlePanel.setBackground(Color.blue); titlePanel.add(title); // adds to center of panel's default BorderLayout.
JLabelfor output is usually bad
It's possible to change the text of a JLabel, although this is
not generally a good idea after the user interface is already displayed.
JTextField is often a better choice.
The use of
JLabel for output is mentioned because some textbooks
display output this way.
Here are some reasons not to use it.
JLabel, but can from a
JLabelsis not serious. You can change the background of a
JTextField, for better or worse.
JTextField, altho you might have to scroll it it's long. There are several possibilities with a
JLabel. You may either not see all of the long text in a
JLabel, or putting long text into a
JLabelmay cause the layout to be recomputed, resulting in a truly weird user experience.
Most JLabels are never changed, except for internationalization, and that is done before the user interface is shown. To change the text, use
yourLabel.setText(String newText); //