Java : 带有文本和图标的 JLabel

Java : JLabel with text and icon

我想问一下是否可以在单个 JLabel 中包含文本图标文本,我的意思是图标位于我的字符串文本的中心。

我设法将文本向左或向右移动图标,但我不知道如何将图标放在中间。

icon to be in the center of my String text

A JLabel 有文本和图标 - 您可以在文本顶部添加标签,但不能是两个文本和一个图标。您可以在适当的布局中使用 3 JLabel 来获得相同的外观。例如,使用 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"));

或者,如果您希望文本位于图像之上,您可以通过设置适当的对齐方式来实现:

JLabel label = new JLabel();
label.setIcon(UIManager.getIcon("OptionPane.errorIcon"));
label.setText("My Text");
label.setHorizontalTextPosition(JLabel.CENTER);
label.setVerticalTextPosition(JLabel.CENTER);

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

一个JLabel可以显示简单HTML:

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

但 HTML 需要更长的渲染时间,因此您可能需要考虑 BoxLayout 方法。