Java Reference
In-Depth Information
}
class MyFrame extends JFrame
{
public MyFrame ( ) {
JButton button1 = new JButton( "First Button" );
JButton button2 = new JButton( "Second Button" );
JButton button3 = new JButton( "Third Button" );
setLayout( new FlowLayout () ) ;
add(button1) ;
add(button2) ;
add(button3) ;
pack() ;
}
}
Initially, all three buttons are displayed on the same line. However, if the window is
resized and made narrower, then the buttons are rearranged on several lines. The idea is
that the first line is filled with components. When the first line becomes full, the second
line is filled with components and so on.
Note that the setLayout method takes as input a layout object. There are several ver-
sions of the constructor of the FlowLayout class. For example, the call setLayout(new
FlowLayout(FlowLayout.LEFT)) will make the components left justified, where 5 pix-
els are left between components by default. Alternatively, the call setLayout(new
FlowLayout(FlowLayout.LEFT,2,10)) will leave a 2-pixel horizontal gap and a 10-pixel
vertical gap between components, where the components will be left justified again. We can
also use the constant FlowLayout.RIGHT to make the layout right justified. By default, the
components are placed in the center.
Usually, several panels are inserted inside a window and the flow layout is used to place
the components in each panel. This is the reason that the flow layout is the default layout
for panels.
12.3 Border Layout
The border layout is the default layout for an object of type JFrame . As Figure 12.1
suggests, one can place a component in one of five locations. When a component is added
to the window, we can specify the area in which to place the component. By default, a
component is placed in the center. Note that only one component can be placed in each
area. If a second component is placed in the same area, then it will be placed on top of
the first component. In our example with one button, the button was placed in the center
using the border layout. Note that the center region takes all unused space - in this case the
whole window. When the window is resized, the center area is the only area that changes
size.
In order to better understand how the border layout works, we will create an example
application that simply adds five panels with different colors in the five areas of the border
layout.
import java .awt .
;
import javax . swing .
;
public class Test {
 
Search WWH ::




Custom Search