import javax.swing.GroupLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; public class GroupLayoutExample extends JFrame { public GroupLayoutExample() { initUI(); } private void initUI() { JPanel panel = new JPanel(); GroupLayout layout = new GroupLayout(panel); panel.setLayout(layout); layout.setAutoCreateGaps(true); layout.setAutoCreateContainerGaps(true); JButton btn1 = new JButton("Button 1"); JButton btn2 = new JButton("Button 2"); JButton btn3 = new JButton("Button 3"); layout.setHorizontalGroup( layout.createSequentialGroup() .addComponent(btn1) .addComponent(btn2) .addComponent(btn3) ); layout.setVerticalGroup( layout.createSequentialGroup() .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(btn1) .addComponent(btn2) .addComponent(btn3)) ); add(panel); pack(); setTitle("Group Layout Example"); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { GroupLayoutExample ex = new GroupLayoutExample(); ex.setVisible(true); }); } }
import javax.swing.GroupLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.SwingUtilities; public class GroupLayoutExample2 extends JFrame { public GroupLayoutExample2() { initUI(); } private void initUI() { JPanel panel = new JPanel(); GroupLayout layout = new GroupLayout(panel); panel.setLayout(layout); JTextArea textArea = new JTextArea(10, 20); JTextField textField = new JTextField(20); JButton button = new JButton("Button"); layout.setHorizontalGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup() .addComponent(textArea) .addComponent(button)) .addComponent(textField) ); layout.setVerticalGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup() .addComponent(textArea) .addComponent(textField)) .addComponent(button) ); add(panel); pack(); setTitle("Group Layout Example 2"); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { GroupLayoutExample2 ex = new GroupLayoutExample2(); ex.setVisible(true); }); } }Example 2 creates a JFrame with a JPanel that contains a JTextArea, JTextField, and a JButton. GroupLayout is used to layout these components. Horizontal and vertical layout is set up using setHorizontalGroup and setVerticalGroup methods. JTextArea and JButton are displayed in a vertical line, and JTextField is displayed below them. Package Library: javax.swing.GroupLayout is part of the javax.swing package, which is one of the built-in packages of the Java Standard Edition (Java SE) library.