How to create a jlabel java swing with detail example

JLabel java swing is often used to display text or images to generate instructions and instructions on the user interface.

Example 1: Creating a simple JLabel java swing
how-to-create-jlabel-java-swing

The result is 3 JLabel java swing as follows (Note file 7826.png is placed in the same package as the picture)

how-to-create-jlabel-java-swing

In the above example, we note the following:
- setLayout (new GridLayout (1, 3, 5, 5)); The set of GridLayout for JFrame with 1 row, 3 columns, columns and rows is 5px. Layout is temporarily interpreted as the layout of objects for Jframe, if there is no layout, the objects will overlap.
- Icon icon = new ImageIcon (); Image file reading command for JLabel.
- Following are 3 commands to create 3 types of JLabel. JLabel has six types of initialization:
+ / JLabel (): Create an empty JLabel instance and an empty string
+ / JLabel (Icon image): Create a JLabel instance that specifies an image
+ / JLabel (Icon image, int horizontalAlignment): Create a JLabel instance that specifies an image and a horizontal alignment.
+ / JLabel (String text): Create a JLabel instance that specifies the text
+ / JLabel (String text, Icon icon, int horizontalAlignment): Create a JLabel instance that specifies text, image, and horizontal alignment.
+ / JLabel (String text, int horizontalAlignment): Create a JLabel instance that specifies text, and horizontal alignment.

In lb3 we have two setVerticalTextPosition and setHorizontalTextPosition functions to position the text vertically (BOTTOM) and horizontally (CENTER). For JLabel only contains text like lb1, if you want to align (left, right, center, ...) use the setHorizontalAlignment (int alignment) method.

Example 2: Set color, background color for JLabel java swing

how-to-create-jlabel-java-swing
The output:
how-to-create-jlabel-java-swing

In this example, create JLabel java swing returns a JLabel java swing with its arguments passed in the text, color, and brackground color. Notice that to set the background color, we need to set the JLabel Opaque to true (default is false).


More about how to use super keyword in java with detail example:

Comments