In this tutorial you will learn:
1. How to Use JLabel
in Swing?
2. How to set image in JLabel?
3. Programming Example
JLabel
is used for displaying unselectable texts and images. It is widely used for displaying label text on swing form. In this article I will show you how to use JLabel in Swing Application.
Programming Example
In this example I will show you to display text and image both.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | package Test.MainJava.com; import java.awt.Color; import java.awt.Font; import java.awt.GridLayout; import javax.swing.*; public class JLabel_Example { JFrame frame; JLabel lblText, lblImage; public void Draw() { //Initialize JLabel. You can also use HTML tag in Label lblText=new JLabel("<html>I am <i>JLabel</i> and Displaying Text<br>in two lines</html>", JLabel.CENTER); lblImage=new JLabel("Icon with Text",new ImageIcon("/home/prashant/Documents/image/checked.png"), JLabel.CENTER); //Changing Label Appearance lblText.setFont(new Font("Arial", Font.BOLD, 16)); lblText.setBackground(Color.GREEN); lblText.setForeground(Color.RED); lblText.setOpaque(true); //Adding Component to Frame frame = new JFrame("Simple JLabel Example"); frame.setSize(400, 300); //Making Layout with 2 row and 1 column frame.setLayout(new GridLayout(2, 1)); frame.add(lblText); frame.add(lblImage); frame.setVisible(true); } public static void main(String[] args) { JLabel_Example j=new JLabel_Example(); j.Draw(); } } |
Output
Explanation:
Consider the following codes
Initialization:
1. You can use HTML Tag in JLabel
for additional customization like changing font-weight, font-style, line-break etc.
1 | lblText=new JLabel("<html>I am <i>JLabel</i> and Displaying Text<br>in two lines</html>", JLabel.CENTER); |
2. Set Picture in Label
1 | lblImage=new JLabel("Icon with Text",new ImageIcon("/home/prashant/Documents/image/checked.png"), JLabel.CENTER); |
3. You can change JLabel appearance like this
1 2 3 4 5 | //Changing Label Appearance lblText.setFont(new Font("Arial", Font.BOLD, 16)); lblText.setBackground(Color.GREEN); lblText.setForeground(Color.RED); lblText.setOpaque(true); |
4. Set Frame Layout with 2 row and 1 column and Set Frame Size like this.
1 2 | frame.setLayout(new GridLayout(2, 1)); frame.setSize(400, 300); |
Summary:
In this chapter you learned how to use JLabel in Swing
for displaying text and image icon. You also learned to change appearance of JLabel. In the next chapter you will learn JTextField, JPasswordField and JTextArea in Swing.