【问题标题】:GridBagLayout - adding margin to constraints to move the component to top from centerGridBagLayout - 向约束添加边距以将组件从中心移动到顶部
【发布时间】:2014-09-18 04:41:24
【问题描述】:

我正在开发我的第一个应用程序来练习布局管理器,我开始学习 GridBagLayout,我想创建一个带有徽标和登录框的登录窗口。

目前我的应用如下所示:


(来源:gyazo.com

我觉得 logo 离登录框太近了,而且离顶部太远了——因此我需要找到一种方法让 logo 从底部留出一个边距,所以它有点到顶部,所以两个组件之间会有一个空格,并且徽标会靠近顶部栏。

GridBagLayout可以做吗?

我尝试将 Insets 设置为 0, 0, 0, 110,它会将徽标向左移动一点,不知道为什么。

@Override
public void init() throws Exception {
    GridBagLayout layout = new GridBagLayout();
    super.setLayout(layout);
    this.loginPane = new JPanel();
    this.loginPane.setSize(400, 400);
    this.loginPane.setBackground(Color.RED);
    JTextField username = new JTextField();
    username.setSize(200, 45);

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

    GridBagConstraints t = new GridBagConstraints();
    t.ipadx = logo.getWidth();
    t.ipady = logo.getHeight();
    t.gridx = 0;
    t.gridy = 0;

    super.add(logoLabel, t);
    t.ipadx = 500;
    t.ipady = 300;
    t.gridwidth = 1;
    t.gridheight = 1;
    t.gridy++;
    super.add(loginPane, t);
}

我该怎么做?

【问题讨论】:

  • 我本人是一个巨大的 Swing 开发人员,我会这样说:如果您花时间学习一个新的 API,我建议学习 JavaFX 而不是 Swing。 Swing 在这一点上几乎被弃用了。

标签: java swing user-interface layout-manager gridbaglayout


【解决方案1】:

您可以使用其他属性更好地控制组件的宽度和高度(以百分比表示)。

  • weightx 指定如何分配额外的水平空间。

  • weighty 指定如何分配额外的垂直空间。

最好在How to Use GridBagLayout上的Swing 教程下展开

试试t.weighty=0.5;,这将在50%-50% 中分开,并将组件也放在中心。让我知道它是否符合您的需要?


  • 使用frame.pack() 而不是frame.setSize(),以根据组件的首选尺寸适合组件。

  • 覆盖getPreferredSize() 以设置JPanel 的首选大小,而不是使用setSize() 方法。

示例代码:

JPanel panel = new JPanel() {

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(..., ...);
    }
};

【讨论】:

    【解决方案2】:

    我尝试将 Insets 设置为 0, 0, 0, 110 并将徽标移动到 左边一点,不知道为什么。

    这是因为插图的顺序是:上、左、下、右

    尝试0, 0, 110, 0 将其从底部偏移。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-05
      • 2015-05-29
      • 1970-01-01
      相关资源
      最近更新 更多