JLabel垂直对齐无法按预期工作 [英] JLabel vertical alignment not working as expected

查看:142
本文介绍了JLabel垂直对齐无法按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这会创建一个在其上方和下方有额外空格的JLabel。我尝试了 setVerticalAlignment(SwingConstants.TOP)但它无效。同样,我不想将JLabel与顶部对齐,但JLabel中的文本应该与顶部对齐。

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.

这里是我的标签看起来像
< img src =https://i.stack.imgur.com/aSe8i.pngalt =在此处输入图像说明>

here is how my label looks like

推荐答案

标签中的文字实际上已与顶部对齐。即使你设置了全部三个:

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.

问题与font-metrics有关。字体为变音符号留下了空间,虽然英文数字甚至字母都不包含大写字母的变音符号,但Arial肯定包含全面的国际字符,包括高于大写字母的字符,例如德语变音符号(ÄÖÜ)或字符包含葡萄牙语变音符号(ÁÂÃ)。

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 (ÁÂÃ).

如果你想要一个快速,简单的解决方案,这可能无法在字体和平台上很好地扩展,你可以使用负数边框上的值以补偿字体指标。

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.

label.setBorder(BorderFactory.createEmptyBorder( -3 /*top*/, 0, 0, 0 ));

如果你想正确修复它,你应该研究一下 FontMetrics 包,因为它有许多可能有用的功能计算正在显示的文本的实际高度和位置,以便您可以将整个字符串移动适当的像素数。

If you want to fix it "right" you should look into learning about the FontMetrics package, 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.

这篇关于JLabel垂直对齐无法按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆