setAlignmentY 未将 BorderLayout 中的 JLabel 居中
对于java新手和该网站来说都是全新的。我在 BorderLayout 的中心面板中添加了一个 JLabel。我希望 JLabel 在面板中居中; setAlignmentX 似乎有效,但 setAlignmentY 无效(标签显示在面板顶部)。这是代码:
centerPanel = new JPanel();
centerPanel.setLayout(new BoxLayout(centerPanel,BoxLayout.Y_AXIS));
JLabel label = new JLabel("This should be centered");
label.setAlignmentX(Component.CENTER_ALIGNMENT);
label.setAlignmentY(Component.CENTER_ALIGNMENT);
centerPanel.add(label);
contentPane.add(centerPanel, BorderLayout.CENTER);
我也尝试过 label.setVerticalAlignment(CENTER);,但无济于事。我在 API 和 Java 教程、本网站以及通过 google 搜索中寻找了答案。谢谢!
new to java and brand new to the site. I have a JLabel added to the center panel of a BorderLayout. I would like the JLabel to be centered in the panel; setAlignmentX appears to work, but setAlignmentY does not (the label appears at the top of the panel). Here is the code:
centerPanel = new JPanel();
centerPanel.setLayout(new BoxLayout(centerPanel,BoxLayout.Y_AXIS));
JLabel label = new JLabel("This should be centered");
label.setAlignmentX(Component.CENTER_ALIGNMENT);
label.setAlignmentY(Component.CENTER_ALIGNMENT);
centerPanel.add(label);
contentPane.add(centerPanel, BorderLayout.CENTER);
I have also tried label.setVerticalAlignment(CENTER);, to no avail. I've looked for an answer in the API and in the Java Tutorials, on this site, and through a google search. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您已经很接近了,试试这个:
Java GUI 编程的众多乐趣之一。如果我说实话,我宁愿把我的眼睛挖出来。
You were close, try this:
One of the many joys of GUI programming in Java. I'd rather poke my eye out if I'm being honest.
我尝试垂直居中对齐
JButton
但遇到问题,它被拉伸了。经过一番摆弄,我发现这个有效:当然它也适用于 JLabel。
I tried to vertically center align
JButton
but I had problem it was stretched. After fiddling I found this works:Of course it works as well for JLabel.