【问题标题】:Cant make GridBagLayout position with weight work无法使 GridBagLayout 位置与重量工作
【发布时间】:2015-01-16 03:17:11
【问题描述】:

我正在尝试制作一个 3x2 网格。在网格中,我想要一张图片和一个相应的单选按钮。所以图片将在(0,0)中,图片在(1,0)中。 我无法让 weightx 和 weighty 系统工作,并且所有组件都保持在一条线上。我现在已经卸下了重量。代码如下所示:

    //the two numbers are corresponding with coordinates. For field00, x=0 and y=0
    GridBagConstraints field00 = new GridBagConstraints();
    field00.fill = GridBagConstraints.HORIZONTAL;
    field00.gridx = 0;
    field00.gridy = 0;
    this.add(nokiaPic, field00);
    GridBagConstraints field10 = new GridBagConstraints();
    field10.fill = GridBagConstraints.HORIZONTAL;
    field10.gridx = 1;
    field10.gridy = 0;
    this.add(nokiaButton, field10);

    GridBagConstraints field01 = new GridBagConstraints();
    field01.fill = GridBagConstraints.HORIZONTAL;
    field01.gridx = 0;
    this.add(princessPic, field01);
    GridBagConstraints field11 = new GridBagConstraints();
    field11.gridx = 1;
    field11.gridy = 1;
    this.add(princessButton, field11);

    To give you an idea:
    +--------+--------+
    |        |        |
    |   pic  | Button |
    |        |        |
    +--------+--------+
    |        |        |
    |   pic  | Button |
    |        |        |
    +--------+--------+
    |        |        |
    |   pic  | Button |
    |        |        |
    +--------+--------+

我知道我没有使用 GridBagConstraints 的常规约定,但我不明白为什么这种方法不能正常工作。我希望你能帮我增加权重,使图片看起来像左列,右行对应的单选按钮。

【问题讨论】:

  • 我“认为:你想要 gridwidthgridheight 描述组件可以扩展的单元格数量
  • 我只希望每个对象占用一个空间。该对象应在两列中彼此下方放置。
  • 觉得你可能需要画一幅画

标签: java swing layout-manager gridbaglayout


【解决方案1】:

在您的情况下,您可以简单地使用GridLayout,但如果您仍想使用GridBagLayout,则使用单个GridBagConstraints

    GridBagConstraints gbc = new GridBagConstraints();
    gbc.fill = GridBagConstraints.HORIZONTAL;
    gbc.gridx = 0;
    gbc.gridy = 0;
    this.add(nokiaPic, gbc);
    gbc.gridx = 1;
    this.add(nokiaButton, gbc);
    gbc.gridx = 0;
    gbc.gridy = 1;
    this.add(princessPic, gbc);
    gbc.gridx = 1;
    this.add(princessButton, gbc);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-12
    • 2015-12-02
    • 2016-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多