Insert an image or icon in JLabel
In this tutorial, we'll create an JLabel with a ImageIcon. Both are in the package javax.swing. JLabel is used to display the text and the image or both, and you can specify the position of the text in relation to the image. By default, the image and text are aligned horizontally. You can even manipulate the pixels in the icon with the setIconTextGap().ImageIcon creates the image from the URL, filename or an array of bits. The most commonly used case is the filename by indicating the path. ImageIcon implements two interfaces:
1- Icon; displays the image specially used with the decoration.
2- Seriazable: is used to read the data stream from the specified path.
The implementation is easy, here are the steps:
1- Create the JFrame.
2- Create the JLabel with text if you need it.
3- Create the ImageIcon:
ImageIcon icon = new ImageIcon(imgUrl); |
jlabel.setIcon(icon); |
JLabel("text" icon, JLabel.CENTER); |
Example
import javax.swing.ImageIcon;After run:
import javax.swing.JFrame;
import javax.swing.JLabel;
public class AddImage {
public static void main(String[] args) {
//Creating JFrame
JFrame frame = new JFrame("JLabel Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(530,600);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
//Image URL
String imgUrl="icon.png";
ImageIcon icon = new ImageIcon(imgUrl);
//Creating JLable with a left
JLabel jlabel = new JLabel(icon, JLabel.CENTER);
//add both JLabel to JFrame
frame.getContentPane().add(jlabel);
frame.validate();
}
}