GridBagLayout不占用所有窗口位置

时间:2015-02-10 21:17:57

标签: java swing awt layout-manager gridbaglayout

你有一个非常简单的问题,为什么我的gridBagLayout不占用我窗户上所有不可取的地方?

这里是代码:

public class FenConnection extends JFrame
{
    private static final long serialVersionUID = 4799549157439445680L;

    private String adresse;
    private int port;

    private JLabel infoLabel;
    private JTextField tf_adresse;
    private JButton boutonConnexion;
    private JTextField tf_port;

    public FenConnection()
    {
        super();

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        this.setResizable(false);
        this.setSize(400, 150);
        this.setTitle("Felix - Connexion");

        adresse = Felix.CONFIGURATION.getString("ADRESSE_CHAT");
        port = Integer.parseInt(Felix.CONFIGURATION.getString("PORT_CHAT"));

        construireFormulaire();
    }

    private void construireFormulaire()
    {
        Container pane = this.getContentPane();
        pane.setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();
        c.fill = GridBagConstraints.BOTH;

        //Construction des labels
        c.gridx = 0;

        c.gridy = 0;
        pane.add(new JLabel("Adresse IP :"), c);

        c.gridy = 1;
        pane.add(new JLabel("Port :"), c);

        c.gridy = 2;
        c.gridwidth = 2;
        infoLabel = new JLabel("Saisir l'adresse et le port du serveur chat");
        pane.add(infoLabel, c);

        //Creation du bouton de connection
        c.gridy = 3;
        c.gridwidth = 2;
        boutonConnexion = new JButton("Connexion");
        pane.add(boutonConnexion, c);

        //Construction des champs de texts
        c.gridx = 1;

        c.gridy = 0;
        tf_adresse = new JTextField(adresse);
        pane.add(tf_adresse, c);

        c.gridy = 1;
        tf_port = new JTextField(port);
        pane.add(tf_port, c);
    }
}

另一个奇怪的事情是,如果我在构造函数的末尾添加this.pack();,它会生成一个非常大且有问题的窗口......我不知道为什么。

我多次使用过此布局,但我从未查看过这个问题。

1 个答案:

答案 0 :(得分:4)

你让weightx和weighty属性默认为0,这意味着它们不会填充可用空间。

尝试为weightx和weighty添加非零

GridBagConstraints c = new GridBagConstraints();
c.weightx = 1;
c.weighty = 1