Advanced Java Programming - Old Questions

7. Discuss group layout with suitable example.

5 marks | Asked in 2071

GroupLayout groups its components and places them in a Container hierarchically. The grouping is done by instances of the Group class. Group is an abstract class, and two concrete classes which implement this Group class are SequentialGroup and ParallelGroup. SequentialGroup positions its child sequentially one after another whereas ParallelGroup aligns its child on top of each other. The GroupLayout class provides methods such as createParallelGroup() and createSequentialGroup() to create groups.

GroupLayout treats each axis independently. That is, there is a group representing the horizontal axis, and a group representing the vertical axis. Each component must exist in both a horizontal and vertical group, otherwise an IllegalStateException is thrown during layout or when the minimum, preferred, or maximum size is requested.

Example:

import java.awt.*;    

import javax.swing.*;    

public class GroupExample {  

    public static void main(String[] args) {  

        JFrame frame = new JFrame("GroupLayoutExample");  

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  

        Container contentPanel = frame.getContentPane();  

        GroupLayout groupLayout = new GroupLayout(contentPanel);  

        contentPanel.setLayout(groupLayout);  

        JLabel clickMe = new JLabel("Click Here");  

        JButton button = new JButton("This Button");  

        groupLayout.setHorizontalGroup(  

                    groupLayout.createSequentialGroup()  

                                .addComponent(clickMe)  

                                .addGap(10, 20, 100)  

                                .addComponent(button));  

        groupLayout.setVerticalGroup(  

                     groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)  

                                .addComponent(clickMe)  

                                .addComponent(button));  

        frame.pack();  

        frame.setVisible(true);  

    }  

}