Java : JLabel with text and icon

Tonys Ansonī Misirgis :

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.

copeg :

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);

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related