How to create a JLabel with an image icon in Java?


Let us create a label with image icon −

JLabel label = new JLabel("SUBJECT ");
label.setIcon(new ImageIcon("E:\
ew.png"));

Now, create another component −

JTextArea text = new JTextArea();
text.setText("Add subject here...");

Align the components with GridBagLayout −

panel.setLayout(new GridBagLayout());

The following is an example to center a label with an image icon −

Example

package my;
import java.awt.GridBagLayout;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;
public class SwingDemo {
   public static void main(String[] args) {
      JFrame frame = new JFrame("Demo Frame");
      JPanel panel = new JPanel();
      JLabel label = new JLabel("SUBJECT ");
      label.setIcon(new ImageIcon("E:\
ew.png"));       JTextArea text = new JTextArea();       text.setText("Add subject here...");       panel.setLayout(new GridBagLayout());       panel.add(label);       panel.add(text);       panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));       frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);       frame.add(panel);       frame.setSize(500, 300);       frame.setVisible(true);    } }

Output

Updated on: 30-Jul-2019

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements