如我所读,调整GridLayout和GrigBagLayout内部组件的大小确实很难。就我而言,我有一个带有2列2行的GridBagLayout。在第一行中,有2个标签,在第二行中,有2个扩展JTable的组件(类型Tablero)。

我的问题是,我不能让这两个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实际上是一项必要条件。

最佳答案

尝试将constraints.weightx = 1;constraints.weighty = 1;添加到JTables约束中。

还要删除这些行:

tablero1.setPreferredSize(new Dimension(400,400));
tablero1.setBounds(0, 0, 400, 400);

关于java - 如何在GridBagLayout中设置组件的大小,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28635448/

10-12 03:49