默认的JLabel
在其边界的中间绘制文本。例如,如果标签的 height
为 20,font height
为 14,则 Y
坐标将为 (20 - 14)/2 = 3
。像这样:
如果想要将文本与 JLabel
bounds
的 TOP
对齐,该怎么办?像这样:
更新:
public class LabelTest extends JFrame {
public LabelTest() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(500, 500);
setLocationRelativeTo(null);
JPanel contentPanel = new JPanel();
contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.X_AXIS));
contentPanel.add(Box.createHorizontalStrut(10));
final JLabel label1 = new JLabel("JLabel");
label1.setVerticalAlignment(SwingConstants.TOP); // by the answer of Kevin Workman, doesn't help
label1.setBorder(BorderFactory.createLineBorder(Color.RED));
label1.setFont(new Font("Arial", Font.PLAIN, 14));
contentPanel.add(label1);
setContentPane(contentPanel);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new LabelTest();
}
});
}
}
最佳答案
您应该打包
框架。如果您这样做,标签中应该没有未使用的空间。如果您想要空白空间,请使用空边框
label.setBorder(new EmptyBorder(0, 0, 5, 0));
top, left, bottom, right
另外,不要设置尺寸,使用布局管理器并让他们为您调整尺寸。设置尺寸会给你。设置尺寸会给您带来僵硬的外观,在不同平台上的外观和性能可能会有所不同。布局管理器将使您的 GUI 更加流畅并适应不同的环境。
参见Laying out Components Within a Container有关使用布局的更多信息
另请参阅Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?
<小时/>关于java - JLabel 文本 Y 绘制坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21459182/