Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java : JLabel with text and icon

I would like to ask if it is possible in a single JLabel to have text icon text, what i mean is the icon to be in the center of my String text.

I managed to move text left or right of the icon but i cant figure out how to put the icon in the middle.

like image 480
Tonys Ansonī Misirgis Avatar asked Jul 16 '16 00:07

Tonys Ansonī Misirgis


1 Answers

icon to be in the center of my String text

A JLabel has text and icon - you can have the label on top of the text, but not two text's and one icon. You can achieve the same look with 3 JLabel's together in the proper Layout. For example, using a BoxLayout:

Box box = Box.createHorizontalBox();
box.add(new JLabel("Text 1"));
JLabel image = new JLabel();
image.setIcon(UIManager.getIcon("OptionPane.errorIcon"));
box.add(image);
box.add(new JLabel("Text 2"));

Alternatively, if you wish the text to be on top of the image you can do so by setting the appropriate alignments:

JLabel label = new JLabel();
label.setIcon(UIManager.getIcon("OptionPane.errorIcon"));
label.setText("My Text");
label.setHorizontalTextPosition(JLabel.CENTER);
label.setVerticalTextPosition(JLabel.CENTER);
like image 96
copeg Avatar answered Oct 12 '22 01:10

copeg