Java Swing How to - Take these labels in exactly required position with GridBagConstraints








Question

We would like to know how to take these labels in exactly required position with GridBagConstraints.

Answer

import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
/* w ww . j  a  v a 2 s. com*/
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Main extends JFrame {

  public Main() {
    add(createPanel(), BorderLayout.NORTH);
  }

  private JPanel createPanel() {
    JPanel p = new JPanel();
    p.setLayout(new GridBagLayout());

    GridBagConstraints c = new GridBagConstraints();
    c.gridx = 0;
    c.gridy = 0;
    c.anchor = GridBagConstraints.BASELINE_LEADING;
    p.add(new JLabel("Loan amount"), c);

    c.gridx++;
    p.add(new JTextField(15), c);

    c.gridx++;
    c.fill = GridBagConstraints.HORIZONTAL;
    c.weightx = 1.0;
    p.add(new JLabel("AUD"), c);

    c.gridx = 0;
    c.gridy++;
    c.fill = GridBagConstraints.NONE;
    c.weightx = 0.0;
    p.add(new JLabel("Loan term"), c);

    c.gridx++;
    p.add(new JTextField(15), c);

    c.gridx++;
    c.fill = GridBagConstraints.HORIZONTAL;
    c.weightx = 1.0;
    p.add(new JLabel("Years"), c);

    return p;
  }

  public static void main(String[] args) {
    Main test = new Main();
    test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    test.pack();
    test.setVisible(true);
  }
}