MigLayout 对齐中心不会使 JLabel 组件居中

Art*_*545 2 java swing miglayout layout-manager

我正在使用MigLayout我发现它很灵活等等,但是我在用它居中放置东西时遇到了问题。我尝试使用,gapleft 50%但似乎百分比数字需要在不同的框架尺寸上改变,因为它也取决于组件的尺寸。因此,如果组件使用 居中gapleft 25%,如果我调整框架的宽度,它将位于不同的位置。

我试过使用 just align center,它根本没有。

我也尝试过new CC().alignX("center").spanX()同样的事情:

图片
(来源:gyazo.com

它坚持左侧,但是当我使用gapleft时它确实有效,为什么?

    super.setLayout(new MigLayout());
    this.loginPane = new LoginPanel();

    BufferedImage logo = ImageIO.read(new File("assets/logo.png"));
    JLabel logoLabel = new JLabel(new ImageIcon(logo));

    super.add(logoLabel, new CC().alignX("center").spanX());
Run Code Online (Sandbox Code Playgroud)

dic*_*c19 5

它坚持左侧,但是当我使用gapleft时它确实有效,为什么?

基于这一行:

super.setLayout(new MigLayout()); // why super? Did you override setLayout() method?
Run Code Online (Sandbox Code Playgroud)

默认情况下,MigLayout行不会填充所有可用宽度,而只会填充显示最长行所需的宽度(基于组件宽度)。话虽如此,您只JLabel适合徽标图像宽度,仅此而已,并且看起来像粘在左侧。您必须告诉布局管理器它必须在实例化时填充所有可用宽度:

super.setLayout(new MigLayout("fillx"));
Run Code Online (Sandbox Code Playgroud)

或者

LC layoutConstraints = new LC();
layoutConstraints.setFillX(true);
super.setLayout(new MigLayout(layoutConstraints);
Run Code Online (Sandbox Code Playgroud)

然后,您的组件约束将按预期工作。


图片

基于此代码片段:

MigLayout layout = new MigLayout("fillx, debug");
JPanel content = new JPanel(layout);

JLabel label = new JLabel("Warehouse");
label.setFont(label.getFont().deriveFont(Font.BOLD | Font.ITALIC, 18));

CC componentConstraints = new CC();
componentConstraints.alignX("center").spanX();
content.add(label, componentConstraints);
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明


注意:您可以通过执行以下操作启用调试功能:

super.setLayout(new MigLayout("fillx, debug"));
Run Code Online (Sandbox Code Playgroud)

或者

LC layoutConstraints = new LC();
layoutConstraints.setFillX(true);
layoutConstraints.setDebugMillis(500);
super.setLayout(new MigLayout(layoutConstraints);
Run Code Online (Sandbox Code Playgroud)