
The window above was produced with the code below, which uses 3 external classes.
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class GridBagLayout{
JFrame frame;
public GridBagLayout() {
initComponents();
}
private void initComponents(){
JTextField text = new JTextField("",10);
JButton but1 = new JButton("button 1");
JButton but2 = new JButton("button 2");
JButton but3 = new JButton("button 3");
JLabel lab0 = new JLabel("Enter a sentence");
JLabel lab1 = new JLabel("test 1");
JLabel lab2 = new JLabel("test 2");
JLabel lab3 = new JLabel("test 3");
frame = new JFrame("TestGridBagLayout");
frame.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
frame.setLayout(new java.awt.GridBagLayout());
frame.add(lab0, new GBConstraints(0,0));
frame.add(text, new GBConstraints(1,0));
frame.add(but1, new GBConstraints(0,1));
frame.add(lab1, new GBConstraints(1,1));
frame.add(but2, new GBConstraints(0,2));
frame.add(lab2, new GBConstraints(1,2));
frame.add(but3, new GBConstraints(0,3));
frame.add(lab3, new GBConstraints(1,3));
frame.setVisible(true);
frame.pack();
}
public static void main(String[] args) {
new GridBagLayout();
}
}
The window below was produced by changing the new GBConstraints
lines above to the lines shown below the picture, the point being that there are several fairly easy ways to tweak the layout to make it look just the way you want--how close together and how vertically aligned, for two issues.

frame.add(lab0, new GBConstraints(0,0).anchor(EAST));
frame.add(text, new GBConstraints(1,0).ipad(100, 0).anchor(WEST));
frame.add(but1, new GBConstraints(0,1));
frame.add(lab1, new GBConstraints(1,1));
frame.add(but2, new GBConstraints(0,2));
frame.add(lab2, new GBConstraints(1,2).insets(15, -15, 5, 5));
frame.add(but3, new GBConstraints(0,3).anchor(EAST));
frame.add(lab3, new GBConstraints(1,3).anchor(WEST));
Note that the second line above has two constraints added onto the GBConstraint; the flexibility is provided by classes Fill
, Anchor
, and GBConstraints
that were provided by @SplungeBob in this thread.