GridBagLayout:如何填充所有空格

gio*_*ozh 8 java swing gridbaglayout

我有一个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();
Run Code Online (Sandbox Code Playgroud)

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

我将消除顶部的空白空间并扩展第二个组件(这是一个可滚动的JTable).我该如何修改代码?

VGR*_*VGR 35

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

如果您c.weighty = 1对包含JTable的组件使用的约束执行操作,则将为该组件分配所有额外的垂直空间.您可能还希望c.weightx = 1这样表填充所有水平空间.


Jor*_*s W 2

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

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