Lecture 9 - Java Swing Layout Management

snottybugbearSoftware and s/w Development

Nov 3, 2013 (3 years and 7 months ago)

224 views

Java Swing
Layout Management
Layout Managers

In early systems, container widgets carried their own
layout algorithms; use
HorizontalStack
,
VerticalStack
as containers

Don’t want to
have to change
container to change layout

JAVA solves this with layout managers

Separate objects that handle a particular style of layout

Desired layout for containers is a property of the container,
set that property rather than changing class hierarchy
public interface
LayoutManager
{
public Dimension
getMinSize
(Widget
containerWidget
);
public Dimension
getDesiredSize
(Widget
containerWidget
);
public Dimension
getMaxSize
(Widget
containerWidget
);
public void
doLayout
(Rectangle
newBounds
, Widget
containerWidget
);
}
public class Widget
{
. . .
other methods and fields . . .
private Dimension
minSize
;
private Dimension
desiredSize
;
private Dimension
maxSize
;
private
boolean
sizesAreValid
;
private
LayoutManager
myLayout
;
public
LayoutManager
getLayoutManager
() { return
myLayout
; }
public void
setLayoutManager
(
LayoutManager
newLayout
)
{
myLayout
=
newLayout
;
invalidate();
}
All container widgets inherit the
same standard layout
code, but
may overwrite it
Setting the layout manager calls
invalidate() so all sizes are
recalculated
Get and set layout managers just
like any other property
Needed for variable intrinsic size
layout
public Dimension
getMinSize
()
{
if (
sizesAreValid
)
return
minSize
;
minSize
=
myLayout.
getMinSize
(this);
sizesAreValid
=true;
}
public Dimension
getDesiredSize
() { . . .
similar to
getMinSize
()
. . .
}
public Dimension
getMaxSize
() { . . .
similar to
getMinSize
()
. . .
}
public void
doLayout
(Rectangle
newBounds
)
{
myLayout.
doLayout
(
newBounds,this
); }
}
Sizes are recalculated using the
methods in the layout manager
Calls to
doLayout
are redirected
to the layout manager
This is how layout managers are organised in
general. Now lets look at how you use them in
Swing........
Layout
Managers in Swing

Creating a layout manager

Consulting managers

Types of
manager

Choosing managers

Other features of component layout

All
covered
very
well here:

http://java.sun.com/docs/books/tutorial/uiswing/layout/using.html
Creating a Layout Manager

Default layout managers

JFrame
,
JDialog
,
JApplet
have
BorderLayout

JPanel
has
FlowLayout

Except when used as a Content Pane (Border Layout
)

Setting the layout manager for a container

JFrame
frame = new
JFrame
();
frame.setLayout
(new
FlowLayout
());

JPanel
contentPane
= new
JPanel
();
contentPane.setLayout
(new
BorderLayout
());
Consulting Layout Managers

Consulted automatically when container may need to
change its appearance
.

These methods result in consultation, but DON’T
trigger new layout

add(), remove(),
removeAll
()
use of these methods suggests a new layout will be need,
but not yet.

getAlignmentX
(),
getAlignmentY
()

getPreferredSize
(),
getMinimumSize
(),
getMaximumSize
()
Consulting Layout Managers

These methods actually result in the manager
performing
layout

JFrame.pack
();

Causes this Window to be sized to fit the preferred size and
layouts of its subcomponents
.

JFrame.show
(),
JFrame.setVisible
(true
);

Shows the
component

JComponent.revalidate
();

This method will automatically be called on this component
when a property value changes. Looks for all dependent
components and calls validate() on them. Validate() causes a
container to lay out its subcomponents again
Types of Layout Manager

BorderLayout

BoxLayout

FlowLayout

GridLayout

GridBagLayout

CardLayout
10
BorderLayout

Five areas

NORTH, SOUTH, EAST, WEST and CENTER

Not all areas must be used

Do not assume a default area for components

Centre gets as much area as possible

Specify location as argument of add method

pane.setLayout
(new
BorderLayout
());

pane.add
(new
JButton
(“Button 1 (NORTH)”),
BorderLayout.NORTH
);

Setting gaps between components (default = 0)

BorderLayout
(
int
horizontalGap
,
int
verticalGap
);

BorderLayout.setHgap
(
int
gap
);

BorderLayout.setVgap
(
int
gap
);
BorderWindow.java
Either in constructor or
later via set/get
11
BoxLayout

Components on top of/ next
to
each other

i.e. horizontal or vertical stack

direction
is your
choice

Tries to size components at preferred height for
Y_AXIS or width for
X_AXIS

Width as largest component width

See above
picture
12
BoxLayout

Space fillers

Rigid: fixed
space between two components

Glue:
taking up no space unless you pull apart the components
that it's sticking to. Helps reposition extra space (default is at
end)

Custom:
Use this to specify a component with whatever
minimum, preferred, and maximum sizes you want
13
BoxLayout

Component sizes

Respects Max, Min and Preferred Sizes of
components

Alignment

Comes into play when not all components are the same
width

Can specify Left (0), Centre (0.5) or Right (1). Or Top
Middle
Bottom

If you are having layout problems, first treat as an
alignment
issue, then examine sizes
.
BoxWindow.java
14
FlowLayout

Very simple
-
JPanel’s
default

Components in row(s)

At preferred size

Alignment

FlowLayout.LEFT

FlowLayout.CENTRE

FlowLayout.RIGHT

Gaps

Default = 5

Can be specified: set
hGap
and
vGap
methods or via
the constructor
FlowWindow.java
15
GridLayout

Grid of cells
-
all same size

Components take all space in a cell

Gaps

default = 5

use
set methods:
hGap
and
vGap

or via arguments to constructor

Re
-
sizing

Cells resize to be as large as possible in given window /
container
GridWindow.java
16
GridBagLayout

Very flexible (and complex!)

Rows can have different heights

Columns can have different lengths

Uses cells in a grid
GridBagLayout
gridbag
= new
GridBagLayout
();
GridBagConstraints
c = new
GridBagConstraints
();
JPanel
pane = new
JPanel
();
pane.setLayout
(
gridbag
);
//
---
For each component to be added to this container:
//
---
...Create the component...
//
---
...Set instance variables in the
GridBagConstraints
instance...
gridbag.setConstraints
(
theComponent
, c);
pane.add
(
theComponent
);
Constraints complex enough to
warrant separate object
17
GridBagLayout

Constraints

set in an instance of a
gridBagConstraints
Object

gridx
and
gridy
-
The row and column of the upper left of the component

Anchor
-
Where to display within cell when component is smaller than it

fill
-
How to size component when cell is larger than components requested
size

insets
-
External padding
-
min space between component and cell edges

ipadx
,
ipady
-
Internal padding
-
What to add to min size of components

weightx
and weighty
-
How to distribute extra space (padding)

gridwidth
and
gridheight
-
Number of columns or rows the component uses

More explanation here:

http://java.sun.com/docs/books/tutorial/uiswing/layout/gridbagConstrai
nts.html
GridBagWindow.java

Example explained very well here:

http://java.sun.com/docs/books/tutorial/uiswing/layout/gridbagExample.html
18
CardLayout

Manages objects (usually
JPanels
) in sets

Works much like tabbed
pane

Metaphor is a stack of playing cards: menu in
CardWindow
selects which is brought to the top of
the deck and so visible

Choose cards by

Asking for card in order added to container

Going backwards or
forwards through the deck

Specifying card by
name
CardWindow.java
19
Choosing Layout Managers

In order to display a component in as much space as
it can get, consider:

BorderLayout

Component in centre

GridBagLayout

fill=
GridBagConstraints.BOTH

BoxLayout

Component specifies very large preferred/maximum
sizes
20
Choosing Layout Managers

To display a few components in a compact row:

JPanel’s
default
FlowLayout

BoxLayout

Display a few components of the same size in rows and
columns

GridLayout

Display a few components in a row or column, with different
spacing between them and custom component sizes

BoxLayout

Display a complex layout that has many components

GridBagLayout

Using
JPanel
grouping and hierarchies
21
Layout Managers
-
Other Layout
Features

Absolute positioning of components

When

How

Customising layout managers

When

How
22
Absolute Positioning

Don’t do it; unless…

component size isn’t affected by changes in container size
or font &
look’n’feel

e.g. desktop panes containing internal frames

custom container performs size & position calculations
particular to container

e.g. split panes
23
Absolute Positioning

Key points from
NoneWindow.java

Instruct window to use no Layout:

.
contentPane.setLayout
(null);

Set components size and position with

XYZ.setBounds
(x, y, width, height);

Set window size with:

window.setSize
(x, y
);
NoneWindow.java
24
Custom Layout Managers

Ensure no existing manager does the job

GridBagLayout
/
BoxLayout

Layout
manager downloads

If your trying to do it, chances are someone else has
done it
already…

DECLARE
use of external code in coursework
25
Custom Layout Managers

Create class which implements Layout Manager interface

e.g.
public class
myManager
implements
LayoutManager

Must have 5 methods required by interface

void
addLayoutComponent
(String, Component)

void
removeLayoutComponent
(Component)

Dimension
preferredLayoutSize
(Container)

Dimension
minimumLayoutSize
(Container)

void
layoutContainer
(Container)

See below URL for more documentation

http://java.sun.com/docs/books/tutorial/uiswing/layout/custom.html
26
Summary

Creating a layout manager

Consulting managers

Types of managers

BorderLayout

GridLayout

BoxLayout

GridBagLayout

FlowLayout

CardLayout

Choosing managers

Absolute positioning

Custom layout
managers