【问题标题】:Java Swing's GridBagLayout will not position component at the top of the grid cellJava Swing 的 GridBagLayout 不会将组件定位在网格单元的顶部
【发布时间】:2013-09-01 00:14:06
【问题描述】:

我试图在代码中尽可能地简化这一点。我已经使用 GridBagLayout 很长时间了,出于某种原因,我从未遇到过这种情况。

JDialog dialog = new JDialog();
dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
dialog.setResizeable(true);

JPanel guiHolder = new JPanel();
guiHolder.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.PAGE_START;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
guiHolder.add(new JLabel("my test"), gbc);

dialog.add(guiHolder);
dialog.setSize(new Dimension(320, 240);
dialog.setSize(true);

JLabel 最终在屏幕中心呈方形。我怎样才能让它到达顶部?我看过How To Use GridBagLayout。我被难住了……

【问题讨论】:

  • 我来看看对话框的布局管理器。
  • 发布的代码甚至无法编译。如果您需要帮助,请发布正确的SSCCE。
  • 不幸的是,我不得不在我的代码中加粗手指。我修复了一个缺陷。希望它现在可以编译。
  • Hopefully it compiles now. 希望还不够好。自己试试。主要方法在哪里?我们不是在这里调试您的代码并使其编译。如果您想暂停,请让我们轻松为您提供帮助。
  • 为我工作。在我修复了您的编译错误并将您的代码放入可运行的演示中后,标签会出现在对话框顶部的中心位置(与 PAGE_START 一样)。

标签: java swing layout user-interface gridbaglayout


【解决方案1】:

如果您修复了编译错误并将代码包装到可运行的演示中,您会发现 GridBagLayout 像宣传的那样工作:

import java.awt.*;
import javax.swing.*;

public class Test implements Runnable
{
  public static void main(String[] args)
  {
    SwingUtilities.invokeLater(new Test());
  }

  public void run()
  {
    JDialog dialog = new JDialog();
    dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
    dialog.setResizable(true);  // fixed mispelling here

    JPanel guiHolder = new JPanel();
    guiHolder.setLayout(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.anchor = GridBagConstraints.PAGE_START;
    gbc.weightx = 1.0;
    gbc.weighty = 1.0;
    guiHolder.add(new JLabel("my test"), gbc);

    dialog.add(guiHolder);
    dialog.setSize(new Dimension(320, 240));
    dialog.setVisible(true);  // fixed wrong method name here
  }
}

【讨论】:

  • -1,发布适当的 SSCCE 是 OP 的责任。我们不应该为他们工作。
  • @camickr 通常我会同意,但在这种情况下,OP 在评论中提出了一个虚假的解决方案,所以我将这个发布给未来可能遇到 GBL 困难的访问者,并且可能会发现这篇文章正在寻找答案。
  • 哇,屋子里有这么多仇恨者。我的开发箱没有互联网连接,所以我输入了我的 SSCCE。帮助 OP 没有错。下次我会更加认真。称我的解决方案为虚假是过度反应。在空气中的所有势利眼下,我快要窒息了。
  • @user1202394 无论如何,我没有势利。您的解决方案不合适。如果您以后必须添加更多内容,您会看到这一点。也许“不正确”或“误导”会更合适。
猜你喜欢
  • 2014-05-01
  • 2020-08-29
  • 1970-01-01
  • 2018-07-30
  • 1970-01-01
  • 1970-01-01
  • 2022-01-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多