【发布时间】:2017-06-04 04:21:22
【问题描述】:
在 Java Swing 中有几个不同的命令可以显式对齐元素。这些命令似乎只在一些极其具体的约束下工作,并且这些约束没有在任何地方记录。大多数时候我想对齐元素,这些命令根本不做任何事情。所以我想知道为什么这些命令没有按照文档所说的那样做,以及如何在 Swing 中对齐元素?
作为参考,这里有一个带有 OK 按钮的 SSCCE,当我们将水平对齐显式设置为居中时,该按钮向左对齐。
import javax.swing.*;
import java.awt.*;
public class E {
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel notificationView = new JPanel();
notificationView.setPreferredSize(new Dimension(300, 145));
notificationView.setLayout(new GridBagLayout());
JPanel content = new JPanel();
content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
JLabel notificationText = new JLabel("Here is some text to display to the user and below this is an ok button.");
content.add(notificationText);
JButton buttonOkNotification = new JButton("OK");
//buttonOkNotification.setHorizontalAlignment(JLabel.CENTER); // does not do anything
//buttonOkNotification.setAlignmentX(Component.CENTER_ALIGNMENT); // does not do anything
content.add(buttonOkNotification);
notificationView.add(content);
frame.add(notificationView);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
【问题讨论】:
-
那些组件属性与布局无关,它们仅用于提示组件如何使用其区域。它们可以用于例如控制 JTextField 中的文本对齐方式。它们不会改变组件在其容器中的布局方式。对于布局管理器,请参阅docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
-
1) “供参考,这里是一个SSCCE..”不,这是一个不可编译的代码sn-p。请仔细阅读minimal reproducible example和Short, Self Contained, Correct Example上的文件。 2) 请参阅Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?(是的。) 3) 提供 ASCII 艺术或简单的图形用户界面 预期 布局图,最小尺寸,如果可调整大小,则具有更大的宽度和高度。 4) 请注意,在按钮上调用的方法是对齐按钮的内容,而不是按钮本身。
-
1) 我没有包含类声明以使其最小化,但我现在将其编辑回帖子中。 2)我没有使用您的链接引用的任何方法。 3) 好的,我将提出一个单独的问题,关于如何为我的特定集成 GUI 实现特定外观。 4)这实际上回答了我在这里发布的一般问题,谢谢。
标签: java swing layout-manager gridbaglayout boxlayout