如何在JLabel中对图标进行右对齐? [英] How to right-justify icon in a JLabel?
问题描述
对于带有图标的JLabel,如果你 setHorizontalTextPosition(SwingConstants.LEADING)
,无论标签有多宽,都会在文本后面立即绘制图标。
For a JLabel with icon, if you setHorizontalTextPosition(SwingConstants.LEADING)
, the icon is painted right after text, no matter how wide the label is.
这对于列表来说特别糟糕,因为图标将遍布整个地方,具体取决于每个项目的文本长度。
This is particularly bad for a list, as the icons would be all over the place depending on how long the text is for each item.
我跟踪代码,似乎在 SwingUtilities#layoutCompoundLabelImpl
中,文本宽度简单地设置为 SwingUtilities2.stringWidth(c ,fm,text)
,并且图标x设置为跟随文本而不考虑标签宽度。
I traced the code and it seems to be that in SwingUtilities#layoutCompoundLabelImpl
, text width is simply set to SwingUtilities2.stringWidth(c, fm, text)
, and icon x is set to follow text without considering label width.
这是最简单的情况:
import java.awt.*;
import javax.swing.*;
public class TestJLabelIcon
{
public static void main(String args[])
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
JLabel c = new JLabel("abc");
c.setHorizontalTextPosition(SwingConstants.LEADING);
c.setHorizontalAlignment(SwingConstants.LEADING);
c.setIcon(UIManager.getIcon("FileChooser.detailsViewIcon"));
c.setBorder(BorderFactory.createLineBorder(Color.RED));
JFrame frame = new JFrame();
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.getContentPane().add(c);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
你可以看到标签总是填充框架但是图标留下来。如果将两个参数都设置为 TRAILING
,则会出现镜像问题。
You can see that label always fills the frame but icon stays put. You'll get the mirror problem if you set both arguments to TRAILING
.
我知道我可以覆盖UI ,或者使用JPanel等。我只是想知道我是否在JLabel中遗漏了一些简单的东西。如果没有,它似乎是一个Java错误。
I know I can override the UI, or use a JPanel, etc. I just wonder if I'm missing something simple in JLabel. If not, it seems like a Java bug.
仅供参考,这是Windows XP上的jdk1.6.0_06。
FYI this is jdk1.6.0_06 on Windows XP.
推荐答案
这是期望的效果吗?
附录:我认为专家组是可行的方法。
Addendum: I think a panel is the way to go.
import java.awt.*;
import javax.swing.*;
public class TestJLabelIcon {
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.setLayout(new GridLayout(0, 1));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createPanel("abc"));
frame.add(createPanel("defghij"));
frame.add(createPanel("klmn"));
frame.add(createPanel("opq"));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private JPanel createPanel(String s) {
JPanel p = new JPanel(new BorderLayout());
p.add(new JLabel(s, JLabel.LEFT), BorderLayout.WEST);
Icon icon = UIManager.getIcon("FileChooser.detailsViewIcon");
p.add(new JLabel(icon, JLabel.RIGHT), BorderLayout.EAST);
p.setBorder(BorderFactory.createLineBorder(Color.blue));
return p;
}
});
}
}
这篇关于如何在JLabel中对图标进行右对齐?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!