java JLabel 垂直对齐无法按预期工作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7115065/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JLabel vertical alignment not working as expected
提问by arpanoid
Font font = Font("Arial", Font.BOLD, 35);
JLabel label = new JLabel("57");
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.LINE_AXIS));
panel.add(label);
This creates a JLabel with an extra space above and below it. I tried setVerticalAlignment(SwingConstants.TOP)
but it not working. Again, I don't want to align JLabel to top but the text inside JLabel should be aligned to top.
这将创建一个 JLabel,上面和下面都有一个额外的空间。我试过了,setVerticalAlignment(SwingConstants.TOP)
但它不起作用。同样,我不想将 JLabel 与顶部对齐,但 JLabel 内的文本应该与顶部对齐。
here is how my label looks like
这是我的标签的样子
回答by Jessica Brown
The text in your label is actually aligned to the top already. Even if you set all three of:
标签中的文本实际上已经与顶部对齐。即使您设置了所有三个:
label.setVerticalAlignment(JLabel.TOP);
label.setVerticalTextPosition(JLabel.TOP);
panel.setAlignmentY(TOP_ALIGNMENT);
you still would find that gap.
你仍然会发现这个差距。
The problem is related to font-metrics. The font leaves space for diacritics, and while English numbers and even letters do not contain diacritics on capital letters, Arial definitely contains a full-breadth of international characters including ones taller than a capital letter, for example, German umlauts (??ü) or characters containing Portuguese diacritics (á??).
该问题与字体度量有关。字体为变音符号留出了空间,虽然英文数字甚至字母不包含大写字母的变音符号,但 Arial 肯定包含全宽的国际字符,包括比大写字母高的字符,例如,德语变音符号 (??ü)或包含葡萄牙语变音符号 (á??) 的字符。
If you want a quick, easy solution that is a hack, that may not scale well across fonts and platforms, you can use a negative value on a border to compensate for the font metrics.
如果您想要一个快速、简单的 hack 解决方案,但可能无法在字体和平台上很好地扩展,您可以在边框上使用负值来补偿字体度量。
label.setBorder(BorderFactory.createEmptyBorder( -3 /*top*/, 0, 0, 0 ));
If you want to fix it "right" you should look into learning about the FontMetricspackage, as it has many functions that could be useful to calculating the actual height and location of the text being displayed, such that you can move the whole string by the appropriate amount of pixels.
如果您想“正确”修复它,您应该研究了解FontMetrics包,因为它有许多功能可用于计算所显示文本的实际高度和位置,以便您可以移动整个字符串适当数量的像素。
回答by trashgod
The arrow in your diagram points to the difference between the glyph's nominal ascentand the maximum ascent, as discussed in FontMetrics
. You can tinker with setBorder(null)
; but for absolute control, you'll have to render the glyphs yourself, as shown here. Fortunately, the digit glyphs of most fonts have a uniform advanceand ascent.
图中的箭头指向字形的标称上升和最大上升之间的差异,如 中所述FontMetrics
。你可以修改setBorder(null)
; 但绝对的控制权,你就必须自己呈现字形,如图所示这里。幸运的是,大多数字体的数字字形都有统一的前进和上升。