Java Unit 3 Notes 1
Java Unit 3 Notes 1
Layout Managers
Layout Managers Requirement
Layout Managers working
Layout Managers types
Flow Layout
BorderLayout
Using Insets in layouts
Layout Managers
Since the Component class defines the setSize() and setLocation() methods, all
Components can be sized and positioned with those methods.
Problem: the parameters provided to those methods are defined in terms of pixels.
Pixel sizes may be different (depending on the platform) so the use of those methods
tends to produce GUIs which will not display properly on all platforms.
NOTE: If you use a Layout Manager, you can no longer change the size and location
of a Component through the setSize and setLocation methods.
Layout Managers
It is very tedious to manually lay out a large number of components and sometimes
the width and height information is not yet available when you need to arrange some
control, because the native toolkit components haven't been realized.
Whenever a container is resized (or sized for the first time), the layout manager is
used to position each of the components within it.
Layout Managers types
There are several different Layout Managers, each of which sizes and positions
its Components based on an algorithm:
FlowLayout
BorderLayout
GridLayout
CardLayout
Grid Bag Layout
The algorithm used by the FlowLayout is to lay out Components like words on
a page: Left to right, top to bottom.
It fits as many Components into a given row before moving to the next row.
Panel aPanel = new Panel();
aPanel.add(new Button("Ok"));
aPanel.add(new Button("Add"));
aPanel.add(new Button("Delete"));
aPanel.add(new Button("Cancel"));
Flow Layout
public FlowLayout()
It creates a layout where components will be centrally aligned, and there will be a gap
of 5 pixels between each components.
public FlowLayout(int alignment)
It creates a layout with the specified alignment, and there will be a gap of 5 pixels
between each components.
Alignment can have one of the following values -
FlowLayout.CENTRE
FlowLayout.LEFT
FlowLayout.RIGHT
FlowLayout.LEADING
FlowLayout.TRAILING
public FlowLayout(int alignment, int horz_gap, int vert_gap)
It creates a layout with specified alignment and horizontal and vertical gab between
components.
Flow Layout
North
South
Program
The values top, left, bottom and right specify the space between Container
and its enclosing window.
To specify this space you need to override getInsets() method provided by
java.awt.Container class. It has the following general form -
public Insets getInsets()
It returns an object of Insets that define the desired space between Container
and its enclosing window.
Example