FlowLayout
and
Boxlayout
BoxLayout
for a JFrame
Recall that to set the layout manager of a container to
BoxLayout
you need to include a reference to
the container in the constructor:
BoxLayout(Container contain, int axis) contain: the container this layout manager is for axis: BoxLayout.X_AXIS — for left to right alignment BoxLayout.Y_AXIS — for top to bottom alignment
A problem with doing this with a JFrame
is that the
container that holds the GUI components is the content pane of the frame.
(JFrame
are made up of several components, which you usually
don't need to worry about.)
To get a reference to the content pane use the
getContentPane()
method of the frame.
Here is how you could change the layout manager of the frame
of the previous example:
setLayout( new BoxLayout( getContentPane(), BoxLayout.Y_AXIS ); add( dataPanel ); add( butPanel );
This would have no visible effect in the example program unless
the size of the frame were made much wider.
A wide frame using FlowLayout
would arrange dataPanel
and butPanel
horizontally.
A wide frame using BoxLayout
would arrange dataPanel
and butPanel
vertically.
Does programming a GUI involve some trial and error?