Java Swing How to - Compare the fill option for GridBagLayout








Question

We would like to know how to compare the fill option for GridBagLayout.

Answer

/*  w w  w .  ja va  2 s .c om*/
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTextField;

public class Main {
  public static void main(String[] args) {
    JLabel userLabel = new JLabel("User Name");
    JLabel passLabel = new JLabel("Password");
    JTextField userText = new JTextField(20);
    JPasswordField passText = new JPasswordField(20);
    JButton loginButton = new JButton("Login");

    JPanel panel = new JPanel(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();

    gbc.insets = new Insets(4, 4, 4, 4);
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.fill = GridBagConstraints.NONE;
    panel.add(userLabel, gbc);

    gbc.gridx = 1;
    gbc.gridy = 0;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    panel.add(userText, gbc);

    gbc.gridx = 0;
    gbc.gridy = 1;
    gbc.fill = GridBagConstraints.NONE;
    panel.add(passLabel, gbc);

    gbc.gridx = 1;
    gbc.gridy = 1;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    panel.add(passText, gbc);

    gbc.gridx = 0;
    gbc.gridy = 2;
    gbc.fill = GridBagConstraints.NONE;
    gbc.anchor = GridBagConstraints.CENTER;
    gbc.gridwidth = 2;
    panel.add(loginButton, gbc);

    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(new JScrollPane(panel));
    f.pack();
    f.setLocationRelativeTo(null);
    f.setVisible(true);
  }
}