Java Swing How to - Align 2 sets/items on either side of center with GridBagLayout








Question

We would like to know how to align 2 sets/items on either side of center with GridBagLayout.

Answer

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
//from   ww w . j a v a  2  s.  c  o m
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

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

class TestPane extends JPanel {
  public TestPane() {
    JLabel longText = new JLabel("Long Long Text");
    JLabel shortText = new JLabel("Short");
    JLabel medText = new JLabel("Medium");

    setLayout(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.anchor = GridBagConstraints.EAST;
    add(longText, gbc);
    addFields(gbc);

    gbc.gridx = 0;
    gbc.gridy++;
    gbc.anchor = GridBagConstraints.EAST;
    add(shortText, gbc);
    addFields(gbc);

    gbc.gridx = 0;
    gbc.gridy++;
    gbc.anchor = GridBagConstraints.EAST;
    add(medText, gbc);
    addFields(gbc);
  }

  protected void addFields(GridBagConstraints gbc) {
    JTextField field1 = new JTextField("0", 5);
    field1.setEnabled(false);
    gbc.anchor = GridBagConstraints.CENTER;
    gbc.gridx++;
    add(field1, gbc);
    gbc.gridx++;
    gbc.insets = new Insets(0, 4, 0, 4);
    add(new JLabel("+"), gbc);
    JTextField field2 = new JTextField(5);
    gbc.gridx++;
    add(field2, gbc);
  }

}