正如我所读到的,在GridLayout和GrigBagLayout中调整组件大小非常困难。在我的例子中,我有一个包含2列和2行的GridBagLayout。在第一行中有2个标签,在第二行中有2个组件(类型Tablero
),它们扩展了JTable。
我的问题是,我不能让这两个JTable填充JFrame直到它的底部。我试过了setSize(), setPreferredSize(), setBounds()
......但他们根本不工作。我也试图通过constraints.fill = GridBagConstraints.VERTICAL/SOUTH/CENTER
来做到这一点......但我绝对没有。
我还尝试在JFrame中设置JPanel的大小,但它不起作用......
这是我的代码:
public static void main(String[] args)
{
JFrame pantalla = new JFrame();
pantalla.getContentPane().setLayout(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
JLabel tab1Label = new JLabel("Tablero 1");
JLabel tab2Label = new JLabel("Tablero 2");
Tablero tablero1 = new Tablero();
Tablero tablero2 = new Tablero();
tablero1.setPreferredSize(new Dimension(400,400));
tablero1.setBounds(0, 0, 400, 400);
tablero1.setBorder(new LineBorder(Color.gray, 2));
constraints.gridx = 0;
constraints.gridy = 0;
constraints.gridwidth = 1;
constraints.gridheight = 1;
constraints.insets = new Insets(0, 0, 20, 0);
pantalla.getContentPane().add(tab1Label, constraints);
constraints.gridx = 1;
constraints.gridy = 0;
constraints.gridwidth = 1;
constraints.gridheight = 1;
constraints.insets = new Insets(0, 0, 20, 0);
pantalla.getContentPane().add(tab2Label, constraints);
constraints.insets = new Insets(0, 0, 0, 0);
constraints.fill = GridBagConstraints.VERTICAL;
constraints.gridx = 0;
constraints.gridy = 1;
constraints.gridwidth = 1;
constraints.gridheight = 1;
pantalla.getContentPane().add(tablero1, constraints);
constraints.fill = GridBagConstraints.VERTICAL;
constraints.gridx = 1;
constraints.gridy = 1;
constraints.gridwidth = 1;
constraints.gridheight = 1;
pantalla.getContentPane().add(tablero2, constraints);
pantalla.pack();
pantalla.setSize(800, 400);
pantalla.setVisible(true);
pantalla.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
结果如下:
我知道还有其他方法可以更容易实现,但使用GridBagLayout实际上是一种讽刺。
答案 0 :(得分:2)
尝试将constraints.weightx = 1;
和constraints.weighty = 1;
添加到JTables约束中。
同时删除这些行:
tablero1.setPreferredSize(new Dimension(400,400));
tablero1.setBounds(0, 0, 400, 400);