Advanced Layout Managers

The advanced layout managers are:

  1. GroupLauout
  2. GridBagLayout
  3. CardLayout
  4. null

GroupLayout

GroupLayout works with the horizontal and vertical layouts separately. The layout is defined for each dimension independently. Each component needs to be defined twice in the layout: once for horizontal and once for vertical.

Components that are added to the GroupLayout will automatically be displayed on the container that the GroupLayout is set for. Therefore, you do not need to add() the components to the container.

GroupLayout components can be placed in a sequential or a parallel arrangement.

  1. With sequential arrangement, the components are placed one after another along an axis.
  2. With parallel they can be aligned, as shown below:

    Parallel components along the x-axis can be aligned:

    Parallel components along the y-axis can be aligned:

 

By including the code below, GroupLayout will automatically place appropriately sized gaps between the components with the GroupLayout and between the GroupLayout and its container.

setAutoCreateGaps(true)
setAutoCreateContainerGaps(true)

GroupLayout Example: (Run Applet)

import javax.swing.*;

public class GroupLayoutDemo extends JApplet
{
    @Override
    public void init()
    {
        this.setContentPane(new View());
    }

    public class View extends JPanel
    {
        public View()
        {
            final JLabel nameLabel = new JLabel("Name:");
            final JLabel addressLabel = new JLabel("Address:");
            final JTextField name = new JTextField(10);
            final JTextArea address = new JTextArea();
            final JButton submit = new JButton("Submit");

            // Set the GroupLayout to be the applet's layout
            final GroupLayout layout = new GroupLayout(this);
            this.setLayout(layout);

            // Automatically set the gaps between components and the container's edges
            layout.setAutoCreateGaps(true);
            layout.setAutoCreateContainerGaps(true);

            // Set the horizontalGroup layout
            // NOTE: that each component will be decleared once
            // in both the horizontal and the vertical axis
            layout.setHorizontalGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addComponent(nameLabel)
                    .addComponent(addressLabel))
                    .addGroup(layout.createParallelGroup(GroupLayout.Alignment.TRAILING)
                    .addComponent(name)
                    .addComponent(address)
                    .addComponent(submit)));

            // Set the verticalGroup layout
            // NOTE: that each component will be decleared once
            // in both the horizontal and the vertical axis
            layout.setVerticalGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(nameLabel)
                    .addComponent(name))
                    .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(addressLabel)
                    .addComponent(address))
                    .addComponent(submit));
        }
    }
}

GridBagLayout

GridBagLayout is similar to GridLayout in that it lays components out in a grid. However, the GridBagLayout can be irregular. Each component that is being placed on a GridBagLayout must have a GridBagConstraints.

To create a GridBagConstraints for a component use:

GridBagConstraints()

After creating a GridBagConstrains for a container, fill in its public variables. They are:

gridx

the column in which the component will be added

gridy

the row in which the component will be added

gridWidth

the number of columns that the component will cover

gridheight

the number of rows that the component will cover

weightx

the portion of extra space to allocate horrizontally

weighty

the portion of extra space to allocate vertically

auchor

specifies the location of the component in its area when the component does not occupy the entire area.

The location can be any of the following:

  • GridBagConstraints.CENTERĀ  // default
  • GridBagConstraints.NORTH
  • GridBagConstraints.NORTHEAST
  • GridBagConstraints.EAST
  • GridBagConstraints.SOUTHEAST
  • GridBagConstraints.SOUTH
  • GridBagConstraints.SOUTHWEST
  • GridBagConstraints.WEST
  • GridBagConstraints.NORTHWEST

After filling the GridBagConstraints for a component we set the component's constraints using:

setConstrants(Component c, GridBagConstranits constraints)

After setting the component's constraints we add the component to the gridBagLayout in the usual way using:

add(Component c)

GridBagLayout Example: (Run Applet)

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

public class GridBagLayoutDemo extends JApplet
{
    @Override
    public void init()
    {
        this.setContentPane(new View());
    }

    public class View extends JPanel
    {
        private final GridBagLayout layout = new GridBagLayout();

        public View()
        {
            super();

            final JButton button1 = new JButton("Button 1");
            final JButton button2 = new JButton("Button 2");
            final JButton button3 = new JButton("Button 3");
            final JButton button4 = new JButton("Button 4");
            final JButton button5 = new JButton("Button 5");


            setLayout(layout);

            setConstraints(button1, 0, 0, 4, 1);
            setConstraints(button2, 0, 1, 2, 2);
            setConstraints(button3, 2, 1, 1, 2);
            setConstraints(button4, 0, 3, 3, 1);
            setConstraints(button5, 3, 1, 1, 3);

            add(button1);
            add(button2);
            add(button3);
            add(button4);
            add(button5);
        }

        private void setConstraints(Component c, int x, int y, int width, int height)
        {
            // If you are using GridBagLayouts, then
            // you should copy this helper method into your code

            final GridBagConstraints constraints = new GridBagConstraints();
            constraints.gridx = x;
            constraints.gridy = y;
            constraints.gridwidth = width;
            constraints.gridheight = height;

            // note that weightx and weighty should usually be set to widthx and widthy
            constraints.weightx = width;
            constraints.weighty = height;
            constraints.fill = GridBagConstraints.BOTH;
            this.layout.setConstraints(c, constraints);
        }
    }
}

CardLayout

The CardLayout arranges components into a deck of cards so that only the top card is visible. Each card can have its own layout.

To create a CardLayout use:

CardLayout()  

To move the cards within the deck use:

first(Container parent)
last(Container parent)
next(Container parent)
previous(Container parent)
show(Container parent, String cardId) // allows randow access to display a given card

CardLayout Example: (Run Applet)

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

public class CardLayoutDemo extends JApplet
{
    @Override
    public void init()
    {
        this.setContentPane(new View());
    }

    public class View extends JPanel implements ActionListener
    {
        private final static String CARD1 = "Text area";
        private final static String CARD2 = "Choice";
        private final JPanel cardsPanel = new JPanel();
        private final CardLayout cardLayout = new CardLayout();
        private final JButton buttonFirst = new JButton("First Card (Card 1)");
        private final JButton buttonLast = new JButton("Last Card (Card 2)");
        private final JButton buttonCard1 = new JButton("Card 1");
        private final JButton buttonCard2 = new JButton("Card 2");

        public View()
        {
            super();

            final JPanel selectorButtonsPanel = new JPanel();
            final JScrollPane card1 = new JScrollPane(new JTextArea("This is card 1"));
            final JComboBox card2 = new JComboBox();

            // deal with selector buttons
            selectorButtonsPanel.setLayout(new GridLayout(4, 1));
            selectorButtonsPanel.add(this.buttonFirst);
            selectorButtonsPanel.add(this.buttonLast);
            selectorButtonsPanel.add(this.buttonCard1);
            selectorButtonsPanel.add(this.buttonCard2);

            // deal with CardLayout
            this.cardsPanel.setLayout(cardLayout);
            this.cardsPanel.add(card1, CARD1);
            this.cardsPanel.add(card2, CARD2);

            card2.addItem("mary");
            card2.addItem("bill");
            card2.addItem("joe");
            card2.addItem("anne");

            this.setLayout(new BorderLayout());
            this.add("West", selectorButtonsPanel);
            this.add("Center", cardsPanel);

            this.buttonFirst.addActionListener(this);
            this.buttonLast.addActionListener(this);
            this.buttonCard1.addActionListener(this);
            this.buttonCard2.addActionListener(this);
        }

        @Override
        public void actionPerformed(ActionEvent e)
        {
            Object source = e.getSource();
            if (source == this.buttonFirst)
            {
                this.cardLayout.first(this.cardsPanel);
            }
            else if (source == this.buttonLast)
            {
                this.cardLayout.last(this.cardsPanel);
            }
            if (source == this.buttonCard1)
            {
                this.cardLayout.show(this.cardsPanel, CARD1);
            }
            else if (source == this.buttonCard2)
            {
                this.cardLayout.show(this.cardsPanel, CARD2);
            }
        }
    }
}

null

Setting the layout manager to null turns the layout manager off for the applet. When no layout is used each component must be sized and placed at specific pixel locations on the container.

Some methods available for use with null layout managers are:

To resize a component use:

setSize(Dimension d)
resize(int width, int height) 

To resize and move a component use:

setBounds(int x, int y, int width, int height)  

To move a component use:

setLocation(int x, int y)

null Layout Example: (Run Applet)

import javax.swing.*;

public class NullLayoutDemo extends JApplet
{
    @Override
    public void init()
    {
        this.setContentPane(new View());
    }

    public class View extends JPanel
    {
        public View()
        {
            super();

            final JButton button1 = new JButton("Button 1");
            final JButton button2 = new JButton("Button 2");

            setLayout(null);

            button1.setSize(100, 100);
            button1.setLocation(10, 10);
            this.add(button1);

            button2.setSize(50, 50);
            button2.setLocation(200, 100);
            this.add(button2);
        }
    }
}

Changing Layouts in Run-time

To change the layout of a container while an applet is running use the setLayout() method followed by the validate() method. The validate() method causes the layout in each container to be recomputed.

Changing Layouts in Run-time example: (Run Applet)

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

public class ChangingLayoutsDemo extends JApplet
{
    @Override
    public void init()
    {
        this.setContentPane(new View());
    }

    public class View extends JPanel implements ActionListener
    {
        private final JButton left = new JButton("left");
        private final JButton center = new JButton("center");
        private final JButton right = new JButton("right");

        public View()
        {
            super();

            this.add(this.left);
            this.add(this.center);
            this.add(this.right);

            this.left.addActionListener(this);
            this.center.addActionListener(this);
            this.right.addActionListener(this);
        }

        @Override
        public void actionPerformed(ActionEvent e)
        {
            final Object source = e.getSource();
            if (source == this.left)
            {
                setLayout(new FlowLayout(FlowLayout.LEFT));
            }
            else if (source == this.center)
            {
                setLayout(new FlowLayout(FlowLayout.CENTER));
            }
            else if (source == this.right)
            {
                setLayout(new FlowLayout(FlowLayout.RIGHT));
            }

            // Force all components to redraw in new position
            this.validate();
        }
    }
}
 
<div align="center"><a href="../versionC/index.html" title="DKIT Lecture notes homepage for Derek O&#39; Reilly, Dundalk Institute of Technology (DKIT), Dundalk, County Louth, Ireland. Copyright Derek O&#39; Reilly, DKIT." target="_parent" style='font-size:0;color:white;background-color:white'>&nbsp;</a></div>