Tonys Ansonī Misirgis
Tonys Ansonī Misirgis

Reputation: 133

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.

Upvotes: 6

Views: 9399

Answers (2)

camickr
camickr

Reputation: 324137

I would like to ask if it is possible in a single JLabel to have text icon text

A JLabel can display simple HTML:

String html = "<html>before <img src=\"file:someFile.jpg\">after</html>";
JLabel label = new JLabel( html );

but HTML takes longer to render so you may want to consider the BoxLayout approach.

Upvotes: 1

copeg
copeg

Reputation: 8348

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

Upvotes: 8

Related Questions