【问题标题】:Java Swing why does aligning only work sometimes?Java Swing 为什么对齐有时只起作用?
【发布时间】: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 exampleShort, 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


【解决方案1】:
JButton buttonOkNotification = new JButton("OK");
//buttonOkNotification.setHorizontalAlignment(JLabel.CENTER); // does not do anything
//buttonOkNotification.setAlignmentX(Component.CENTER_ALIGNMENT); // does not do anything

请注意,按钮上调用的方法是对齐按钮的内容,而不是按钮本身。这些约束通常只有在组件被拉伸到大于其首选尺寸时才会变得相关或引人注目。这种拉伸通常是它所在容器的布局和约束的结果。一个很好的例子是BorderLayout

  • 要水平而不是垂直拉伸组件,请将其添加到PAGE_STARTPAGE_END
  • 要垂直而不是水平拉伸组件,请将其添加到LINE_STARTLINE_END
  • 要垂直水平拉伸组件,请将其添加到CENTER

FlowLayout 进行对比。流式布局不会垂直或水平拉伸组件,而是始终保持它们的首选大小。


要在面板对齐按钮组件,需要对布局使用约束。这可以在构造上完成,例如:

new FlowLayout(FlowLayout.RIGHT); // aligns all child components to the right hand side

但是在向容器中添加组件时更常见。例如。在向GridBagLayout 添加组件时,它可能如下所示:

gridBagConstraints.anchor = GridBagConstraints.NORTHWEST;
panel.add(new JLabel("North West"), gridBagConstraints);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-06
    • 2014-03-09
    • 1970-01-01
    • 1970-01-01
    • 2011-10-08
    • 2021-06-21
    • 2011-07-08
    • 2012-03-22
    相关资源
    最近更新 更多