Next: Case study: Temperature conversion.
Up: Composing GUIs.
Previous: The JPanel class.
Layouts
Textbook: Section 12.6
There are several categories of GUI classes of which you
should be aware:
- The JFrame class
- Component classes (JButton, JTextField, JPanel)
- Listening interfaces (ActionListener)
- Event classes (ActionEvent)
- Container classes (Container, JPanel)
- LayoutManager classes (FlowLayout, BorderLayout, GridLayout)
We've covered all but the last. Now we're covering the last, composed of
classes that implement the LayoutManager interface.
The layout classes tell a container class how it should
lay out the components it contains. What we can do is to set the layout
of a container, telling it to change its approach for handling
components.
Each container has such a method, called setLayout().
- void setLayout(LayoutManager manager)
- Changes the layout technique for the container.
Each container also has two methods for putting components into the
container.
- void add(Component what)
- Inserts what into the panel, using the default placement.
- void add(Component what, Object info)
- Inserts what into the panel, using info as
information about where the object should be placed.
BorderLayout
We've actually already seen the BorderLayout class: It's the default
layout for a JFrame's container. Creating a BorderLayout is simple:
- BorderLayout()
- Creates a BorderLayout object.
When you add something to a container that's using the BorderLayout, you
will generally use the add() method that takes an info
parameter, and you will pass something like BorderLayout.NORTH
saying on which border to place the component (or
BorderLayout.CENTER to place the component in the middle).
FlowLayout
The FlowLayout class is even simpler: It places the components in
left-to-right order. Each component gets sized to its preferred
size. When the components fill the row, they start being placed in the
next row.
- FlowLayout()
- Creates a FlowLayout object.
With a container using FlowLayout, you'll generally use the
add() that doesn't take an info
parameter.
FlowLayout is the default layout for a JPanel.
GridLayout
In the GridLayout class, components are placed left-right,
top-down in a strict grid. Each component is resized to fill its grid
space.
- GridLayout(int rows, int columns)
- Creates a GridLayout object, represent the layout strategy with
rows rows and columns columns.
Next: Case study: Temperature conversion.
Up: Composing GUIs.
Previous: The JPanel class.