Course Content‎ > ‎Session 7‎ > ‎

Layout Management

The Java platform supplies five commonly used layout managers: BorderLayout, BoxLayout, FlowLayout, GridBagLayout and GridLayout. By default, every container has a layout manager. All JPanel objects use a FlowLayout by default, whereas content panes (the main containers in JApplet, JDialog, and JFrame objects) use BorderLayout by default. As a rule, the only time you have to think about layout managers is when you create a JPanel or add components to a content pane. If you don't like the default layout manager that a panel or content pane uses, you can change it to a different one. Just invoke the container's setLayout method.

    import java.awt.Container;
    setLayout(LayoutManager m);
    void add(Component c); // adds a component to this container

When you add components to a panel or a content pane, the arguments you specify to the add method depend on the layout manager that the panel or content pane you are using. So be sure to check the API documentation for the layout manager for details.

Border Layout   

BorderLayout is the default layout manager for every content pane of JFrame. The content pane is the main container in all frames, applets, and dialogs. A BorderLayout has five areas available to hold components: north, south, east, west, and center. All extra space is placed in the center area.

    
Here is a sample code illustrating the above layout: 

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;

    public class BorderLayoutSample extends JFrame
    {
        public BorderLayoutSample()
        {
            Container contentPane = getContentPane();
            contentPane.setLayout(new BorderLayout());
            
            JLabel northLabel = new JLabel("Label in North", JLabel.CENTER);
            JLabel southLabel = new JLabel("Label in South", JLabel.CENTER);
            JLabel eastLabel = new JLabel("Label in East");
            JLabel westLabel = new JLabel("Label in West");
            JButton centerButton = new JButton ("Button in Center");
            
            contentPane.add(northLabel, BorderLayout.NORTH);
            contentPane.add(southLabel, BorderLayout.SOUTH);
            contentPane.add(westLabel, BorderLayout.WEST);
            contentPane.add(eastLabel, BorderLayout.EAST);
            contentPane.add(centerButton, BorderLayout.CENTER);
            
            addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e)
                {
                    System.exit(0);
                }
            });
        }
        
        public static void main(String args[])
        {
            BorderLayoutSample window = new BorderLayoutSample();
            window.setTitle("BorderLayout Example");
            window.pack();
            window.setVisible(true);
        }
    } //BorderLayoutSample class

    


Analysis of the program 

The title of this window is set to BorderLayout Example. In the above example, first of all we create a content pane, by calling getContentPane() method. Thereafter, four labels are added to the content pane, using JLabel constructor. Text of these labels is based on their locations in the content pane, that is EAST, WEST, SOUTH, NORTH. A button is added in the center, using JButton constructor. We will look at these user interface components in detail in a short while. For now, you can see that displayed text is passed as an argument to the constructor, to create these components.       

BoxLayout

The BoxLayout class puts components in a single row or column. This class takes care of the components requested maximum sizes and also lets you align components. Here is an example illustrating the above concept:

    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;

    public class BoxLayoutSample extends JFrame
    {
        public BoxLayoutSample()
        {
            Container contentPane = getContentPane();
            
            //Create panel to add components
            JPanel mainPanel = new JPanel();
            JPanel panelX= new JPanel();
            JPanel panelY = new JPanel();
            
            //Setting BoxLayout along x and y-axis
            panelX.setLayout(new BoxLayout(panelX, BoxLayout.X_AXIS));
            panelY.setLayout(new BoxLayout(panelY, BoxLayout.Y_AXIS));
            
            //Adding components to x-axis
            JLabel labelX = new JLabel("Label along x-axis");
            JLabel labelX2 = new JLabel("Label along x-axis");
            JButton buttonX = new JButton("Button along x-axis");
            
            panelX.add(labelX);
            panelX.add(buttonX);
            panelX.add(labelX2);
            
            //Adding components to y-axis
            JLabel labelY = new JLabel("Label along y-axis");
            JLabel labelY2 = new JLabel("Label along y-axis");
            
            panelY.add(labelY);
            panelY.add(labelY2);
            
            //Adding both panels to main panel
            mainPanel.add(panelX);
            mainPanel.add(panelY);
            
            contentPane.add(mainPanel);
            
            addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e)
                {
                    System.exit(0);
                }
            });
        }
        
        public static void main(String args[])
        {
            BoxLayoutSample mainWindow = new BoxLayoutSample();
            mainWindow.setTitle("BoxLayout Sample");
            mainWindow.pack();
            mainWindow.setVisible(true);
        }
    }

Analysis of the program 

In the above example, a main panel is created, using the constructor for JPanel. This main panel has two panels  panelX and panelY. panelX has two labels and a button and panelY has two labels with the BoxLayout manager. panelX  arranges the labels along the x-axis by calling the BoxLayout manager and panelY arranges the labels along the y-axis. This is done, by calling the BoxLayout constructor. The first parameter of the constructor specifies the container and the second specifies the major axis of the BoxLayout. 

Sample output will look like this:

    


FlowLayout

FlowLayout is the default layout manager for every JPanel. This layout manager simply lays out components from left to right, starting new rows, if necessary.

Constructs a new FlowLayout with the specified alignment (left, center, right). The FlowLayout class has three constructors:

    public FlowLayout()
    
    public FlowLayout(int alignment)
    
    public FlowLayout(int alignment, int horizontalGap, int verticalGap)

FlowLayout uses 5 for the default gap value.  

    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;

    public class FlowLayoutSample extends JFrame
    {
        public FlowLayoutSample()
        {
            JPanel panel = new JPanel();
            panel.setLayout (new FlowLayout());
            panel.add(new JButton("Button 1"));
            panel.add(new JButton("Button 2"));
            panel.add(new JButton("Button 3"));
            panel.add(new JButton("Button 4"));
            panel.add(new JButton("Button 5"));
            panel.add(new JButton("Button 6"));
            
            this.getContentPane().add(panel);
            this.setSize(400, 200);
            this.setVisible(true);
        }
        
        protected void processWindowEvent(WindowEvent e)
        {
            super.processWindowEvent(e);
            if(e.getID() == WindowEvent.WINDOW_CLOSING)
            {
                System.exit(0);
            }
        }
        
        public static void main(String args[])
        {
            new FlowLayoutSample();
        }
    }

Analysis of the program 

In the above example, a panel is created, using the constructor for JPanel. Six buttons are added to this panel, using FlowLayout manager. FlowLayout is constructed by calling the FlowLayout constructor with no parameter. This puts six buttons in a row. Since, two buttons dont fit in the first row, they are moved to the second row with center alignment. If you wish to define components alignment, you can use FlowLayout constructor, which takes alignment as the parameter. Sample output of the above program will look like this:

    


GridLayout 

GridLayout simply makes a bunch of components equal in size and displays them in the requested number of rows and columns. A GridLayout places components in a grid of cells. Each component takes all the available space within its cell, and each cell is exactly the same size. If you resize the GridLayout window, you'll see that the GridLayout changes the cell size so that the cells are as large as possible, given the space available to the container. There are two constructors, which can be used to create this layout:

    public GridLayout(int rows, int columns)
    
    public GridLayout(int rows, int columns)
    
    int horizontalGap, int verticalGap) 

Gap is taken as zero, if no value is defined for it. One of the arguments, rows or columns, must be non-zero. 

Here is an example code, illustrating this layout:

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;

    public class GridLayoutSample extends JFrame
    {
        public GridLayoutSample()
        {
            Container contentPane = getContentPane();
            contentPane.setLayout(new GridLayout(0,2));
            
            contentPane.add(new JButton("Button 1"));
            contentPane.add(new JButton("Button 2"));
            contentPane.add(new JButton("Button 3"));
            contentPane.add(new JButton("Button 4"));
            contentPane.add(new JButton("Button 5"));
            
            addWindowListener(new WindowAdapter){
                public void windowClosing(WindowEvent e) {
                    {
                        System.exit(0);
                    }
                }});
        }
        
        public static void main(String args[])
        {
            GridLayoutSample window = new GridLayoutSample();
            window.setTitle("GridLayout");
            window.pack();
            window.setVisible(true);
        }
    }

Analysis of the program

In this example code, five button components are created. These five components are added to the content pane in the frame. Thereafter, GridLayout constructor is called to create two columns and as many rows as necessary. Buttons are put in the grid of cells, as shown below in the sample output:

    


GridBagLayout

GridBagLayout is the most sophisticated, flexible layout manager the Java platform provides. This layout manager aligns components by placing them within a grid of cells, allowing some components to span more than one cell. The rows in the grid aren't necessarily all the same height; similarly, grid columns can have different widths. You can set the following GridBagConstraints instance variables: 

1. gridx, gridy

Used to specify the row and column at the upper left of the component. The leftmost column has address gridx = 0 and the top row has address gridy = 0.

2. gridwidth, gridheight
Specifies the number of columns (for gridwidth) or rows (for gridheight) in the component's display area. These constraints specify the number of cells the component uses, not the number of pixels it uses. Default value is 1.

3. Fill
Used when the component's display area is larger than the component's requested size to determine whether and how to resize the component.

4. ipadx, ipady
Specifies the internal padding: how much to add to the minimum size of the component. The default value is zero

5. insets
Specifies the external padding of the component -- the minimum amount of space between the component and the edges of its display area. The value is specified as an Insets object. By default, each component has no external padding.

6. anchor
Used when the component is smaller than its display area to determine where (within the area) to place the component. Valid values (defined as GridBagConstraints constants) are CENTER (the default), NORTH, NORTHEAST, EAST, SOUTHEAST, SOUTH, SOUTHWEST, WEST, and NORTHWEST.

7. weightx, weighty
Weights are used to determine how to distribute space among columns (weightx) and among rows (weighty).

Here is an example illustrating this layout:

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;

    public class GridBagSample extends JFrame
    {
        public GridBagSample()
        {
            JButton button;
            Container contentPane = getContentPane();
            
            GridBagLayout gridbag = new GridBagLayout();
            GridBagConstraints c = new GridBagConstraints();
            
            contentPane.setLayout(gridbag);
            
            button = new JButton("Button 1");
            c.gridx = 1;
            c.gridy = 0;
            c.gridwidth = 1;
            
            gridbag.setConstraints(button, c);
            contentPane.add(button);
            
            button = new JButton("Button 2");
            c.ipady = 40;      
            c.weighty = 1.0;  
            c.anchor = GridBagConstraints.SOUTH;
            c.insets = new Insets(10,0,0,0); 
            c.gridx = 1;      
            c.gridwidth = 2;   //2 columns wide
            c.gridy = 2;       //third row
            gridbag.setConstraints(button, c);
            contentPane.add(button);
            
            addWindowListener(new WindowAdapter()
            {
                public void windowClosing(WindowEvent e)
                {
                    System.exit(0);
                }
            });
        }
        
        public static void main(String args[])
        {
            GridBagSample window = new GridBagSample();
            
            window.setTitle("GridBagLayout Example");
            window.pack();
            window.setVisible(true);
        }
    }

Analysis of the program 

The above example uses GridBagLayout manager for the components. It creates GridBagLayout manager and GridBagConstraints. Instance variables in the GridBagConstraint object are set to the default value, before each component is added to the container. It then uses the setConstraints method to record all the constraint values for that component. Here, in Button 2, we have increased the height, by using ipady attribute. Padding is added, using insets.  

    


Comments