Java-Swing:Introduction to Swing - Introduction to Layout Managers

From Juneday education
Jump to: navigation, search


A layout manager is responsible for placing and resizing the components of a GUI. You typically set the layout manager using the setLayout() method on a container.

We will not introduce all available layout managers, but instead show you code for a few of them, and we refer to the Oracle tutorials listed at the bottom of this page, for further reading.

Border Layout

Screenshot of BorderLayout

This layout manager lets you place components in five regions of the container:

  • NORTH and SOUTH - top and botton. Lets components keep their preferred height, but will expand them maximally horizontally
  • EAST and WEST - left and right edges. Lets components keep their preferred width, but will expand them maximally vertically
  • CENTER. Expands the component maximally in all directions
Screenshot of BorderLayout - resized window

We think this is best shown with two screenshots, shown in this section.

Code example:

We strongly encourage you to read up on this and other layout managers, over at Oracle's tutorials site:

We also have examples in the longer Swing examples, like the Address book GUI chapter.


Screenshot of FlowLayout

FlowLayout lets you add components sequentially, which will add them from left-to-right if they fit on one row, and wrap to next row if they don't fit. Again, we refer to the code exampel and the two screenshots shown in this section.

Source code:

Screenshot of FlowLayout, resized

We strongly encourage you to read more about FlowLayout at Oracle's tutorials:

This layout is also used in the JLabel, JButton and JTextField examples from previous chapers.


Screenshot of GridLayout

GridLayout is simple to use, but not very pretty. You declare a grid for the components (rows, cols), and you add them from top left-to right, row by row. All components will expand maximally in all directions.

The source code example for GridLayout can be found here:

Screenshot of GridLayout, resized

We also refer to the screenshots shown in this section, for a visual example of what goes on when you resize the window.

Please also read the Oracle tutorial on GridLayout:

Teaching materials


Further reading

Where to go next

« PreviousBook TOCNext »