【问题标题】:GridBagLayout: how to fill all empty spacesGridBagLayout:如何填充所有空白
【发布时间】:2013-07-19 22:15:15
【问题描述】:

我有一个 JFrame,其中包含一些使用 gridBagLayout(3 行,一列)的 JPanel。这是我的代码:

Container main_container = getContentPane();
GridBagLayout layout = new GridBagLayout();
main_container.setLayout(layout);
GridBagConstraints c = new GridBagConstraints();

StatoMagazzini jpanel_stato_magazzini = new StatoMagazzini();
c.gridx = 1;
c.gridy = 2;
c.fill = GridBagConstraints.BOTH;
layout.setConstraints(jpanel_stato_magazzini, c);

AcquistoLotto jpanel_acquisto = new AcquistoLotto(i, jpanel_stato_magazzini);
c.gridx = 1;
c.gridy=1;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.FIRST_LINE_START;
layout.setConstraints(jpanel_acquisto, c);

ButtonPanel jpanel_button_panel = new ButtonPanel(i);
c.gridx=1;
c.gridy=3;
c.anchor = GridBagConstraints.CENTER;
layout.setConstraints(jpanel_button_panel, c);

main_container.add(jpanel_acquisto);
main_container.add(jpanel_stato_magazzini);
main_container.add(jpanel_button_panel);
pack();

这就是结果(一个丑陋的结果):https://docs.google.com/file/d/0Bxi2arJ2Dv9xbEo0Smd5QUN4UGc/edit?usp=sharing

我将消除顶部的空白并扩展第二个组件(即可滚动的 JTable)。我应该如何修改代码?

【问题讨论】:

    标签: java swing gridbaglayout


    【解决方案1】:

    当 GridBagLayout 的空间超出其需要时,它会使用每个单元格的 weightxweighty 属性分配额外的空间。如果没有单元格具有非零权重属性,则不会将额外空间分配给任何单元格,而是将所有单元格居中,并调整为它们首选的宽度/高度。

    如果您对包含 JTable 的组件使用的约束执行c.weighty = 1,则该组件将被分配所有额外的垂直空间。您可能还想做c.weightx = 1,这样表格将填满所有水平空间。

    【讨论】:

      【解决方案2】:

      您可以将容器的布局设置为 BorderLayout(或等效的),并使用 GridBagLayout 创建一个额外的 JPanel 并将其添加到容器中

      由于 Borderlayout,JPanel 会占用尽可能多的空间

      【讨论】:

      • 很好,只需使用没有 gridbaglayout 的borderlayout 就可以了。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-09
      • 1970-01-01
      • 2010-10-26
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 2017-04-20
      相关资源
      最近更新 更多