Java GroupLayout layout components in grid

Description

Java GroupLayout layout components in grid



import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

class MyPanel extends JPanel {

  public MyPanel() {
    JLabel fNameLbl = new JLabel("First Name");
    JTextField fNameFld = new JTextField();
    JLabel lNameLbl = new JLabel("Last Name");
    JTextField lNameFld = new JTextField();
    JButton saveButt = new JButton("Save");

    GroupLayout groupLayout = new GroupLayout(this);
    setLayout(groupLayout);//from  w  ww . ja v a  2 s .  c  om

    groupLayout.setAutoCreateGaps(true);

    // Create gaps around the componet touching the parent contain (JPanel)
    groupLayout.setAutoCreateContainerGaps(true);

    // create a sequence of column groups.
    GroupLayout.SequentialGroup columnGroups = groupLayout.createSequentialGroup();

    // add each column horizontally.

    // first column
    columnGroups.addGroup(groupLayout.createParallelGroup().addComponent(fNameLbl).addComponent(lNameLbl));

    // second column
    columnGroups.addGroup(groupLayout.createParallelGroup().addComponent(fNameFld).addComponent(lNameFld)
        .addGroup(Alignment.TRAILING, groupLayout.createSequentialGroup().addComponent(saveButt) // group pushing button
                                                                                                 // to right
        ));

    // set horizontal groups
    groupLayout.setHorizontalGroup(columnGroups);

    // create a sequence of row groups.
    GroupLayout.SequentialGroup rowGroups = groupLayout.createSequentialGroup();

    // add each row vertically.

    // first row
    rowGroups.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE).addComponent(fNameLbl).addComponent(fNameFld));

    // second row
    rowGroups.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE).addComponent(lNameLbl).addComponent(lNameFld));

    // third row
    rowGroups.addGroup(groupLayout.createSequentialGroup().addComponent(saveButt));

    // set vertical groups
    groupLayout.setVerticalGroup(rowGroups);
  }
}

public class Main {
  public static void main(String[] args) {
    // create frame for Main
    JFrame frame = new JFrame("java2s.com");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.add(new MyPanel());
    frame.setSize(300, 210);
    frame.setVisible(true);
  }
}



PreviousNext

Related