Java-Swing:Introduction to Swing - Introduction to Layout Managers
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.
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
We think this is best shown with two screenshots, shown in this section.
Code example: Borderline.java
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.
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: Flow.java
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.
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: Grid.java.
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:
- Vimeo link: TODO - put in Java extra lectures channel when done