In our simple Swing program, we specified the location of our various components inside the window with some constants: BorderLayout.CENTER, BorderLayout.SOUTH etc. In general, a window has a particular layout, and that when we add a component to the window, we add it in a particular position in that layout.
By default— and this is why our example worked— windows have what is called a border layout. This layout is represented by the Java class java.awt.BorderLayout (most layouts live inside the awt package, for historic reasons, rather than the newer javax.swing package), hence that is the class that the constants EAST, WEST, CENTER etc come from. With a BorderLayout, the window is assumed to contain five positions, as illustrated in Figure 1.
This layout is useful in various typical situations where our window consists of some "main content", plus some other auxiliary component, for example:
To specify the layout of a frame, we would write something like:
Layout constructors can typically take parameters specifying margins between components. We didn't actually include such a line in our example, because BorderLayout is the default type of layout and we decided to make do with the default margins. We'll see later that the way we used it actually isn't so typical, but it got us started.
The layout is responsible for resizing components to best fit the available space. The component in the CENTER position will be as large as possible, whilst not violating the sizing constraints of other components. (We'll learn more about such constraints later.) Components in the NORTH and SOUTH positions will generally be stretched to the width of the window, but won't be stretched vertically if the centre component can be stretched instead.
Another type of layout that it sometimes useful is GridLayout. As you might expect, this lays components out in a grid fashion, with a given number of rows and columns. You construct a GridLayout by saying how many rows and columns you require; you can also leave one of these two numbers as zero to mean "as many rows/columns as necessary":
// Lay components out as 4 rows of 3 columns frame.setLayout(new GridLayout(4, 3)); // Lay components out with 5 columns frame.setLayout(new GridLayout(0, 5));
When adding items to a frame with a GridLayout, no position is specified. Items are placed row by row (from top to bottom), column by column (from left to right). We'll see a GridLayout example on the next page.
Another layout is FlowLayout, which lays its components out like lines on a page of English text, going from left to right, and on to multiple lines where necessary. We'll see in a moment that the Swing Box class has superseded FlowLayout for some uses.
Next: panels and boxes
On the next page, we look at how we can put these layouts together to form more complex layouts using JPanels and Boxes.
Copyright © Javamex UK 2009. All rights reserved.