Java Swing GUI

JLabel – Java Swing – Example

In this tutorial, we are going to see an example of JLabel in Java Swing. JLabel is a java Swing class. JLabel is a field to display a short string or an image or both. JLabel is only used to display text or images and it can’t get focus. JLabel is inactive to capture events such as mouse focus or keyboard focus. By default, labels are centered vertically but the user can change the alignment of JLabel.
 

JLabel constructors class:
JLabel constructors
Description
JLabel() Create a blank label without text or image.
JLabel(String s) Create a new label with the specified string.
JLabel(Icon i) Create a new label with an image on it.
JLabel(String s, Icon i, int align) Create a new label with a string, an image and a specified horizontal alignment

 

Commonly used methods of JLabel class:
  • getIcon() : returns the image that the label displays
  • setIcon(Icon i) : sets the image that the label will display
  • getText() : returns the text displayed in the label
  • setText(String s) : sets the text of the label
 

Example of JLabel in Java Swing:
import javax.swing.*;
 
public class Main 
{
    public static void main(String[] args) 
    {
        //Create a new frame
        JFrame frame = new JFrame("JLabel Example");
        //Create a label to display centered text
        JLabel label = new JLabel("Welcome to StackHowTo!", JLabel.CENTER);
        //Add label to frame
        frame.add(label);
    
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(250, 250);
        frame.setVisible(true);
    }
}

Output:


mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *