Perhaps JLabelis the simplest Swing’s GUI component which simply renders a text message or an icon or both on screen. This article presents common practices when using JLabelin Swing development.
Table of content:
JLabel label = new JLabel("This is a basic label");
JLabel label = new JLabel(); label.setText("This is a basic label");
JLabel label = new JLabel(new ImageIcon("images/attention.jpg"));
Image:
This is the common way to display an image/icon in Swing.
String iconPath = "/net/codejava/swing/jlabel/Color.png"; Icon icon = new ImageIcon(getClass().getResource(iconPath)); JLabel label = new JLabel(icon);
JLabel label = new JLabel("A label with icon and text", new ImageIcon("images/attention.jpg"), SwingConstants.CENTER);
In this case, we can set the gap between the icon and the text as follows:
label.setIconTextGap(10);
That will set 10 pixels gap between the icon and the text.
JLabel label = new JLabel("Enter first name:", SwingConstants.RIGHT); JLabel label = new JLabel(new ImageIcon("images/attention.jpg"), SwingConstants.LEFT);
frame.add(label); dialog.add(label); panel.add(label); applet.getContentPane().add(label);
frame.add(label, BorderLayout.CENTER); panel.add(label, gridbagConstraints);
label.setFont(new java.awt.Font("Arial", Font.ITALIC, 16)); label.setOpaque(true); label.setBackground(Color.WHITE); label.setForeground(Color.BLUE);
NOTE:by default, the label’s background is transparent, so if you want to set background, you have to set the label’s opaque property to true.
label.setText("<html><font color=red size=4><b>WARNING!</b></html>");
JLabel label = new JLabel("<html><i>This label has <br>two lines</i><html>");
Image:
A JLabelis usually used for labeling a component such as a JTextField. If we want to allow the users accessing a text field using shortcut key (mnemonic), use the following code:
JTextField textEmail = new JTextField(20); JLabel label = new JLabel("Enter e-mail address:"); label.setLabelFor(textEmail); label.setDisplayedMnemonic('E');
Image:
You can notice that the ‘E’ letter in the label in underlined, so the users can type Alt + E to get focus on the text field.
For reference, we created a Swing program that demonstrates various techniques mentioned when working with JLabelcomponent. The program looks like this:
You can download the program’s source code in the attachment section.