Graphical User Interfaces in Java

Chapter 
20 
 
Graphical 
User 
Interfaces
Chapter
 
Goals
To 
use 
layout 
managers 
to 
arrange user‑interface 
components  
in 
a
container
To 
use 
text 
components 
to 
capture and display 
text 
in 
a  
graphical
application
To 
become 
familiar 
with 
common 
user-interface 
components,  
such 
as
radio 
buttons, 
check 
boxes, 
and
 
menus
To 
browse 
the 
Java 
documentation
 
effectively
undefined
Layout
 
Management
Build 
user 
interface 
by 
adding 
components 
into
containers.  
Use a 
layout 
manager 
to 
place 
the
 
components.
JFrame 
uses 
Flow 
layout 
by
 
default.
undefined
Border
 
Layout
Components are placed toward areas of a container NORTH, EAST,
 
SOUTH,
WEST, or
 
CENTER.
Specify one when adding
 
components:
panel.setLayout(new
 
BorderLayout());
panel.add(component,
 
BorderLayout.NORTH);
F
i
g
u
r
e
 
1
 
C
o
m
p
o
n
e
n
t
s
 
E
x
p
a
n
d
 
t
o
 
F
i
l
l
 
S
p
a
c
e
 
i
n
 
t
h
e
 
B
o
r
d
e
r
 
L
a
y
o
u
t
undefined
Grid
 
Layout
Components 
are 
placed 
in 
boxes 
in 
a 
simple 
table 
arrangement.
Specify 
the 
size (rows 
then 
columns) 
of 
the
 
grid.
Then 
add 
components 
which 
will 
be placed 
from 
the 
upper left,
across, 
then
 
down.
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4,
 
3));
buttonPanel.add(button7);
buttonPanel.add(button8);
buttonPanel.add(button9);
buttonPanel.add(button4);
. .
 
.
F
i
g
u
r
e
 
2
 
T
h
e
 
G
r
i
d
 
L
a
y
o
u
t
undefined
Achieving 
Complex
 
Layouts
Create 
complex 
layouts 
by 
nesting
 
panels.
Give 
each 
panel 
an 
appropriate layout
 
manager.
Panels 
have 
invisible 
borders, 
so 
you 
can use 
as 
many
 
panels
as 
you 
need 
to 
organize
 
components.
JPanel keypadPanel = new JPanel();
keypadPanel.setLayout(new BorderLayout());
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4,
 
3));
buttonPanel.add(button7);
buttonPanel.add(button8);
// . .
 
.
keypadPanel.add(buttonPanel,
 
BorderLayout.CENTER);
JLabel display = new JLabel("0");
keypadPanel.add(display,
 
BorderLayout.NORTH);
F
i
g
u
r
e
 
3
 
N
e
s
t
i
n
g
 
P
a
n
e
l
s
undefined
Using
 
Inheritance
Use 
inheritance 
for 
complex 
frames.  
Design 
a
subclass 
of
 
JFrame:
Store components as instance
 
variables.  Initialize
them in the constructor of your  subclass.
Easy 
to 
add helper 
methods 
to 
organize
 
code.
public class FilledFrame extends JFrame
{
// Use instance variables for components private JButton button;
private JLabel
 
label;
private static final int FRAME_WIDTH = 300;
private static final int FRAME_HEIGHT = 100;
public
 
FilledFrame()
{
// Now we can use a helper method
 
createComponents();
// It is a good idea to set the size in the frame constructor
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
private void createComponents() {
button = new JButton("Click
 
me!");
label = new JLabel("Hello,
 
World!");
JPanel panel = new JPanel();
 
panel.add(button);
panel.add(label);
add(panel);
}
}
undefined
Using
 
Inheritance
FillledFrameViewer2 
main
 
method:
public class
 
FilledFrameViewer2
{
public static void main(String[] args)
{
JFrame frame = new FilledFrame();
frame.setTitle("A frame with two
 
components");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Self 
Check
 
20.1
 
What happens if you place two buttons in the northern position of a border
layout?  Try it out with a small
 
program.
A
n
s
w
e
r
:
 
O
n
l
y
 
t
h
e
 
s
e
c
o
n
d
 
o
n
e
 
i
s
 
d
i
s
p
l
a
y
e
d
.
Self 
Check
 
20.2
 
How do you add two buttons to the northern position of a frame so that they
are  shown next to each
 
other?
A
n
s
w
e
r
:
 
F
i
r
s
t
 
a
d
d
 
t
h
e
m
 
t
o
 
a
 
p
a
n
e
l
,
 
t
h
e
n
 
a
d
d
 
t
h
e
 
p
a
n
e
l
 
t
o
 
t
h
e
n
o
r
t
h
 
e
n
d
 
o
f
 
a
 
f
r
a
m
e
.
Self 
Check
 
20.3
 
How can you stack three buttons one above the
 
other?
A
n
s
w
e
r
:
 
P
l
a
c
e
 
t
h
e
m
 
i
n
s
i
d
e
 
a
 
p
a
n
e
l
 
w
i
t
h
 
a
 
G
r
i
d
L
a
y
o
u
t
 
t
h
a
t
h
a
s
 
t
h
r
e
e
 
r
o
w
s
 
a
n
d
 
o
n
e
 
c
o
l
u
m
n
.
Self 
Check
 
20.4
 
What happens when you place one button in the northern position of a border
layout  and another in the center position? Try it out with a small program if you
aren’t
 
sure.
A
n
s
w
e
r
:
 
T
h
e
 
b
u
t
t
o
n
 
i
n
 
t
h
e
 
n
o
r
t
h
 
s
t
r
e
t
c
h
e
s
 
h
o
r
i
z
o
n
t
a
l
l
y
 
t
o
 
f
i
l
l
 
t
h
e
w
i
d
t
h
 
o
f
 
t
h
e
 
f
r
a
m
e
.
 
T
h
e
 
h
e
i
g
h
t
 
o
f
 
t
h
e
 
n
o
r
t
h
e
r
n
 
a
r
e
a
 
i
s
 
t
h
e
 
n
o
r
m
a
l
h
e
i
g
h
t
.
 
T
h
e
 
c
e
n
t
e
r
 
b
u
t
t
o
n
 
f
i
l
l
s
 
t
h
e
 
r
e
m
a
i
n
d
e
r
 
o
f
 
t
h
e
 
w
i
n
d
o
w
.
Self 
Check
 
20.5
Some calculators have a double-wide 0 button, as shown below. How can
 
you
achieve
 
that?
 
A
n
s
w
e
r
:
 
T
o
 
g
e
t
 
t
h
e
 
d
o
u
b
l
e
-
w
i
d
e
 
b
u
t
t
o
n
,
 
p
u
t
 
i
t
 
i
n
 
t
h
e
 
s
o
u
t
h
 
o
f
 
a
p
a
n
e
l
 
w
i
t
h
 
b
o
r
d
e
r
 
l
a
y
o
u
t
 
w
h
o
s
e
 
c
e
n
t
e
r
 
h
a
s
 
a
 
3
 
×
 
2
 
g
r
i
d
 
l
a
y
o
u
t
w
i
t
h
 
t
h
e
 
k
e
y
s
 
7
,
 
8
,
 
4
,
 
5
,
 
1
,
 
2
.
 
P
u
t
 
t
h
a
t
 
p
a
n
e
l
 
i
n
 
t
h
e
 
w
e
s
t
 
o
f
a
n
o
t
h
e
r
 
b
o
r
d
e
r
 
l
a
y
o
u
t
 
p
a
n
e
l
 
w
h
o
s
e
 
e
a
s
t
e
r
n
 
a
r
e
a
 
h
a
s
 
a
 
4
 
×
 
1
 
g
r
i
d
l
a
y
o
u
t
 
w
i
t
h
 
t
h
e
 
r
e
m
a
i
n
i
n
g
 
k
e
y
s
.
Self 
Check
 
20.6
 
Why does the 
FilledFrameViewer2
 
class declare the frame variable to have class
JFrame
, 
not
 
FilledFrame
?
A
n
s
w
e
r
:
 
T
h
e
r
e
 
w
a
s
 
n
o
 
n
e
e
d
 
t
o
 
i
n
v
o
k
e
 
a
n
y
 
m
e
t
h
o
d
s
 
t
h
a
t
 
a
r
e
s
p
e
c
i
f
i
c
 
t
o
 
F
i
l
l
e
d
F
r
a
m
e
.
 
I
t
 
i
s
 
a
l
w
a
y
s
 
a
 
g
o
o
d
 
i
d
e
a
 
t
o
 
u
s
e
 
t
h
e
m
o
s
t
 
g
e
n
e
r
a
l
 
t
y
p
e
 
w
h
e
n
 
d
e
c
l
a
r
i
n
g
 
a
 
v
a
r
i
a
b
l
e
.
Self 
Check
 
20.7
 
How many Java source files are required by the application in Section 20.1.3
when  we use inheritance to declare the frame
 
class?
A
n
s
w
e
r
:
 
T
w
o
:
 
F
i
l
l
e
d
F
r
a
m
e
V
i
e
w
e
r
2
,
 
F
i
l
l
e
d
F
r
a
m
e
.
Self 
Check
 
20.8
 
Why
 
does
 
the
 
createComponents
 
method
 
of
 
FilledFrame
 
call
 
add(panel)
,
whereas
 
the
 
main
 
method
 
of
 
FilledFrameViewer
 
calls
 
frame.add(panel)
?
A
n
s
w
e
r
:
 
I
t
s
 
a
n
 
i
n
s
t
a
n
c
e
 
m
e
t
h
o
d
 
o
f
 
F
i
l
l
e
d
F
r
a
m
e
,
 
s
o
 
t
h
e
f
r
a
m
e
 
i
s
 
t
h
e
 
i
m
p
l
i
c
i
t
 
p
a
r
a
m
e
t
e
r
.
Common 
Error
 
20.1
You 
add 
components like 
buttons 
or
 
labels:
panel.add(button);
panel.add(label);
panel.add(carComponent);
Default 
size 
for 
component 
is 
0 
by 
0 
pixels 
so 
car
 
component
will 
not 
be
 
visible.
Use
 
setPreferredSize
:
carComponent.setPreferredSize(new Dimension(CAR_COMPONENT_WIDTH,
 
CAR_COMPONENT_HEIGHT));
Only 
needed 
for 
painted
 
components.
undefined
Processing 
Text
 
Input
Dialog 
boxes 
allows 
for 
user
 
input.
Popping 
up 
a 
separate 
dialog 
box 
for 
each 
input 
is 
not 
a 
natural
user
 
interface.
Most 
graphical 
programs 
collect 
text 
input through 
text 
fields.
The 
JTextField class 
provides 
a 
text
 
field.
Specify 
the 
width 
for 
the 
text
 
field.
If 
the 
user 
exceeds 
this 
width, 
text 
will 
‘scroll’
 
left.
final int FIELD_WIDTH =
 
10;
final JTextField rateField = new
 
JTextField(FIELD_WIDTH);
F
i
g
u
r
e
 
4
 
A
n
 
A
p
p
l
i
c
a
t
i
o
n
 
w
i
t
h
 
a
 
T
e
x
t
 
F
i
e
l
d
undefined
Add 
a 
Label 
and
 
a 
Button
Add 
a 
label 
to 
describe 
the
 
field:
JLabel rateLabel = new JLabel("Interest Rate:
 
");
Add 
a 
button for 
user 
to 
indicate 
input 
is
 
complete.
actionPerformed
 
method
 
can
 
use
 
getText
 
to
 
get
 
input
 
as
 
a
String
.
Convert to a numeric value if used
 
for
calculations.
class AddInterestListener implements
 
ActionListener
{
public void actionPerformed(ActionEvent
 
event)
{
double rate = Double.parseDouble(rateField.getText());
double interest = balance * rate /
 
100;
balance = balance + interest;
resultLabel.setText("Balance: " +
 
balance);
}
}
section_2_1/
InvestmentFrame2.java
/**
A 
frame 
that 
shows 
the 
growth 
of 
an 
investment with variable
 
interest.
*/
public class 
InvestmentFrame2 
extends 
JFrame
{
private static final int 
FRAME_WIDTH = 
450
;
private static final int 
FRAME_HEIGHT =
 
100
;
private static final double 
DEFAULT_RATE = 
5
;
private static final double 
INITIAL_BALANCE =
 
1000
;
private 
JLabel
 
rateLabel;
private 
JTextField
 
rateField;
private 
JButton button;
private 
JLabel resultLabel;
private double
 
balance;
public
 
InvestmentFrame2()
{
balance =
 
INITIAL_BALANCE;
resultLabel = 
new 
JLabel(
"Balance: " 
+ balance);
1
import
 
java.awt.event.ActionEvent;
2
import
 
java.awt.event.ActionListener;
3
import
 
javax.swing.JButton;
4
import
 
javax.swing.JFrame;
5
import
 
javax.swing.JLabel;
6
import
 
javax.swing.JPanel;
7
import
 
javax.swing.JTextField;
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
createTextField();
createButton();
 
 
undefined
Text
 
Areas
Create 
multi-line 
text 
areas 
with 
a 
JTextArea 
object.
Set 
the 
size 
in 
rows 
and
 
columns.
final int ROWS = 10; // Lines of
 
text
final int COLUMNS = 30; // Characters in each row
JTextArea textArea = new JTextArea(ROWS,
 
COLUMNS);
Use 
the 
setText 
method 
to 
set 
the 
text of 
a
 
text 
field 
or 
text
area.
textArea.append(balance +
 
"\n");
Can 
use 
the 
text 
area 
for 
display purposes
 
only.
textArea.setEditable(false);
undefined
TextComponent
 
Class
JTextField
 
and
 
JTextArea
 
are
 
subclasses
 
of
JTextComponent
.
setText
 
and 
setEditable
 
are
 
declared
 
in
 
the
JTextComponent
 
class.
Inherited by JTextField and
 
JTextArea.
append
 
method 
is 
only 
declared 
in 
JTextArea
.
F
i
g
u
r
e
 
5
 
A
 
P
a
r
t
 
o
f
 
t
h
e
 
H
i
e
r
a
r
c
h
y
 
o
f
 
S
w
i
n
g
 
U
s
e
r
-
I
n
t
e
r
f
a
c
e
 
 
C
o
m
p
o
n
e
n
t
s
undefined
Scrolling
To 
add scroll 
bars, 
use
 
JScrollPane
:
JScrollPane scrollPane = new
 
JScrollPane(textArea);
F
i
g
u
r
e
 
6
 
T
h
e
 
I
n
v
e
s
t
m
e
n
t
 
A
p
p
l
i
c
a
t
i
o
n
 
w
i
t
h
 
a
 
T
e
x
t
 
A
r
e
a
 
I
n
s
i
d
e
 
S
c
r
o
l
l
 
B
a
r
s
section_2_2/
InvestmentFrame3.java
/**
A 
frame 
that 
shows 
the 
growth 
of 
an 
investment with variable interest,
using a text
 
area.
*/
public class 
InvestmentFrame3 
extends 
JFrame
{
private static final int 
FRAME_WIDTH = 
400
;
private static final int 
FRAME_HEIGHT =
 
250
;
private static final int 
AREA_ROWS = 
10
;
private static final int 
AREA_COLUMNS =
 
30
;
private static final double 
DEFAULT_RATE = 
5
;
private static final double 
INITIAL_BALANCE =
 
1000
;
private 
JLabel rateLabel;
private 
JTextField
 
rateField;
private 
JButton button;
private 
JTextArea
 
resultArea;
private double
 
balance;
1
import
 
java.awt.event.ActionEvent;
2
import
 
java.awt.event.ActionListener;
3
import
 
javax.swing.JButton;
4
import
 
javax.swing.JFrame;
5
import
 
javax.swing.JLabel;
6
import
 
javax.swing.JPanel;
7
import
 
javax.swing.JScrollPane;
8
import
 
javax.swing.JTextArea;
9
import
 
javax.swing.JTextField;
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public
 
InvestmentFrame3()
 
 
Self 
Check
 
20.9
 
What happens if you omit the first 
JLabel
 
object in the program of Section 20.2.1?
A
n
s
w
e
r
:
 
T
h
e
n
 
t
h
e
 
t
e
x
t
 
f
i
e
l
d
 
i
s
 
n
o
t
 
l
a
b
e
l
e
d
,
 
a
n
d
 
t
h
e
 
u
s
e
r
 
w
i
l
l
 
n
o
t
k
n
o
w
 
i
t
s
 
p
u
r
p
o
s
e
.
Self 
Check
 
20.10
 
If a text field holds an integer, what expression do you use to read its
 
contents?
A
n
s
w
e
r
:
 
I
n
t
e
g
e
r
.
p
a
r
s
e
I
n
t
(
t
e
x
t
F
i
e
l
d
.
g
e
t
T
e
x
t
(
)
)
Self 
Check
 
20.11
 
What is the difference between a text field and a text
 
area?
A
n
s
w
e
r
:
 
A
 
t
e
x
t
 
f
i
e
l
d
 
h
o
l
d
s
 
a
 
s
i
n
g
l
e
 
l
i
n
e
 
o
f
 
t
e
x
t
;
 
a
 
t
e
x
t
 
a
r
e
a
 
h
o
l
d
s
m
u
l
t
i
p
l
e
 
l
i
n
e
s
.
Self 
Check
 
20.12
 
Why did the 
InvestmentFrame3
 
program call
resultArea.setEditable(false)
?
A
n
s
w
e
r
:
 
T
h
e
 
t
e
x
t
 
a
r
e
a
 
i
s
 
i
n
t
e
n
d
e
d
 
t
o
 
d
i
s
p
l
a
y
 
t
h
e
 
p
r
o
g
r
a
m
o
u
t
p
u
t
.
 
I
t
 
d
o
e
s
 
n
o
t
 
c
o
l
l
e
c
t
 
u
s
e
r
 
i
n
p
u
t
.
Self 
Check
 
20.13
 
How would you modify the 
InvestmentFrame3
 
program if you didn’t want to use
scroll
 
bars?
A
n
s
w
e
r
:
 
D
o
n
t
 
c
o
n
s
t
r
u
c
t
 
a
 
J
S
c
r
o
l
l
P
a
n
e
 
b
u
t
 
a
d
d
 
t
h
e
resultArea
 
object 
directly 
to 
the 
panel.
undefined
C
h
o
i
c
e
s
GUI 
components 
for
 
selections:
Radio Buttons For a small set of mutually exclusive choices.
Check Boxes For a binary choice.
Combo Boxes For a large set of
 
choices.
undefined
Radio
 
Buttons
Only 
one 
button 
in 
a 
set 
can 
be 
selected.
Selecting 
a 
button 
clears 
previous
 
selection.
In an old fashioned radio, pushing down one station button released the
 
others.
Create 
each 
button
 
individually.
Add 
all 
buttons in 
the 
set 
to 
a 
ButtonGroup
 
object:
JRadioButton smallButton = new JRadioButton("Small");
JRadioButton mediumButton = new JRadioButton("Medium");
JRadioButton largeButton = new JRadioButton("Large");
ButtonGroup group = new ButtonGroup();
group.add(smallButton);
group.add(mediumButton);
group.add(largeButton);
Use 
isSelected
 
to 
find 
out 
whether 
a 
button 
is 
selected, 
like:
if (largeButton.isSelected()) { size = LARGE_SIZE;
 
}
undefined
Radio 
Button
 
Panels
Use a 
panel 
for 
each 
set 
of 
radio
 
buttons.
The 
default 
border 
for 
a 
panel 
is 
invisible 
(no 
border).
You can 
add 
a 
border 
to 
a 
panel 
to 
make 
it
 visible.
Also 
add 
a
 
title.
JPanel panel = new JPanel();
panel.add(smallButton);
panel.add(mediumButton);
panel.add(largeButton);
panel.setBorder(new TitledBorder(new
 
EtchedBorder(),"Size"));
User 
Interface
 
Components
F
i
g
u
r
e
 
7
 
A
 
C
o
m
b
o
 
B
o
x
,
 
C
h
e
c
k
 
B
o
x
e
s
,
 
a
n
d
 
R
a
d
i
o
 
B
u
t
t
o
n
s
undefined
Check
 
Boxes
A 
check 
box 
has 
two 
states: checked 
and 
unchecked.
Use 
for 
choices 
that 
are 
not 
mutually
 
exclusive.
For example in Figure 7, text may be
 
Italic,
Bold, both or
 
neither.
Because 
check 
box 
settings 
do 
not 
exclude 
each 
other, 
you 
do
not 
need 
to 
place 
a 
set 
of 
check 
boxes 
inside 
a 
button
 
group.
Radio 
buttons 
are 
round 
and 
have 
a 
black 
dot 
when 
selected.
Check 
boxes 
are 
square 
and 
have 
a 
check 
mark 
when
 
selected.
Construct 
a 
text
 
box:
JCheckBox italicCheckBox = new
 
JCheckBox("Italic");
Use 
isSelected
 
to 
find 
out 
whether 
a 
check 
box 
is 
selected.
undefined
Combo
 
Boxes
A 
combo 
box 
is 
a 
combination 
of 
a 
list 
and 
a 
text 
field.
Clicking 
the 
arrow 
to 
the 
right of 
the 
text 
field 
opens 
the 
list 
of
selections.
Use a 
combo 
box 
for 
a 
large 
set 
of
 
choices.
Use 
when 
radio 
buttons 
would 
take 
up 
too 
much 
space.
It 
can 
be
 
either:
Closed (shows one selection).
Open, showing multiple
 
selections.
It 
can 
also 
be
 
editable:
Type a selection into a blank
 
line.
facenameCombo.setEditable();
undefined
Adding 
and 
Selecting
 
Items
Add 
text 
‘items’ 
to 
a 
combo 
box 
that will 
show 
in 
the
 
list:
JComboBox facenameCombo = new JComboBox();
facenameCombo.addItem("Serif");
facenameCombo.addItem("SansSerif");
. .
 
.
Use 
the 
getSelectedItem
 
method 
to 
return 
the 
selected 
item
(as 
an
 
Object).
Combo boxes 
can 
store 
other 
objects 
in 
addition 
to 
strings, 
so
casting 
to 
a 
string 
may be
 
required:
String selectedString = (String)
 
facenameCombo.getSelectedItem();
F
i
g
u
r
e
 
8
 
A
n
 
O
p
e
n
 
C
o
m
b
o
 
B
o
x
undefined
Handling 
Input
 
Events
Radio 
buttons, 
check 
boxes, 
and 
combo 
boxes 
generate
 
an
ActionEvent
 
when 
selected.
In 
FontViewer
 
program, 
listener 
gets 
all 
events.
Simply check 
the 
state 
of 
each 
component 
using
 
isSelected
and 
getSelectedItem
 
methods.
Then 
redraw 
the 
label 
with 
the 
new
 
font.
F
o
n
t
V
i
e
w
e
r
F
i
g
u
r
e
 
9
 
T
h
e
 
C
o
m
p
o
n
e
n
t
s
 
o
f
 
t
h
e
 
F
o
n
t
 
F
r
a
m
e
section_3/
FontViewer.java
1
 
import
 
javax.swing.JFrame;
2
3
 
/**
4
 
This 
program 
allows the user to 
view 
font
 
effects.
5
 
*/
6
 
public class
 
FontViewer
7
 
{
8
 
public static void 
main(String[]
 
args)
9
 
{
10
JFrame frame = 
new
 
FontFrame();
11
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
12
frame.setTitle(
"FontViewer"
);
13
frame.setVisible(
true
);
14
 
}
15
 
}
section_3/
FontFrame.java
/**
This 
frame 
contains a text 
sample and 
a control panel
to 
change 
the font of the
 
text.
*/
public class 
FontFrame 
extends
 
JFrame
{
private static final int 
FRAME_WIDTH = 
300
;
private static final int 
FRAME_HEIGHT =
 
400
;
private 
JLabel
 
label;
private 
JCheckBox italicCheckBox;
private 
JCheckBox boldCheckBox;
private 
JRadioButton smallButton;
private 
JRadioButton
 
mediumButton;
private 
JRadioButton largeButton;
private 
JComboBox facenameCombo;
private 
ActionListener
 
listener;
1
import
 
java.awt.BorderLayout;
2
import
 
java.awt.Font;
3
import
 
java.awt.GridLayout;
4
import
 
java.awt.event.ActionEvent;
5
import
 
java.awt.event.ActionListener;
6
import
 
javax.swing.ButtonGroup;
7
import
 
javax.swing.JButton;
8
import
 
javax.swing.JCheckBox;
9
import
 
javax.swing.JComboBox;
10
import
 
javax.swing.JFrame;
11
import
 
javax.swing.JLabel;
12
import
 
javax.swing.JPanel;
13
import
 
javax.swing.JRadioButton;
14
import
 
javax.swing.border.EtchedBorder;
15
import
 
javax.swing.border.TitledBorder;
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
Constructs the
 
frame.
Self 
Check
 
20.14
 
What is the advantage of a 
JComboBox
 
over a set of radio buttons? What is the
disadvantage?
A
n
s
w
e
r
:
 
I
f
 
y
o
u
 
h
a
v
e
 
m
a
n
y
 
o
p
t
i
o
n
s
,
 
a
 
s
e
t
 
o
f
 
r
a
d
i
o
 
b
u
t
t
o
n
s
 
t
a
k
e
s
u
p
 
a
 
l
a
r
g
e
 
a
r
e
a
.
 
A
 
c
o
m
b
o
 
b
o
x
 
c
a
n
 
s
h
o
w
 
m
a
n
y
 
o
p
t
i
o
n
s
 
w
i
t
h
o
u
t
u
s
i
n
g
 
u
p
 
m
u
c
h
 
s
p
a
c
e
.
 
B
u
t
 
t
h
e
 
u
s
e
r
 
c
a
n
n
o
t
 
s
e
e
 
t
h
e
 
o
p
t
i
o
n
s
 
a
s
e
a
s
i
l
y
.
Self 
Check
 
20.15
 
What happens when you put two check boxes into a button group? Try it out if
 
you
are not
 
sure.
A
n
s
w
e
r
:
 
I
f
 
o
n
e
 
o
f
 
t
h
e
m
 
i
s
 
c
h
e
c
k
e
d
,
 
t
h
e
 
o
t
h
e
r
 
o
n
e
 
i
s
 
u
n
c
h
e
c
k
e
d
.
Y
o
u
 
s
h
o
u
l
d
 
u
s
e
 
r
a
d
i
o
 
b
u
t
t
o
n
s
 
i
f
 
t
h
a
t
 
i
s
 
t
h
e
 
b
e
h
a
v
i
o
r
 
y
o
u
 
w
a
n
t
.
Self 
Check
 
20.16
How can you nest two etched borders, like
 
this?
 
A
n
s
w
e
r
:
 
Y
o
u
 
c
a
n
t
 
n
e
s
t
 
b
o
r
d
e
r
s
,
 
b
u
t
 
y
o
u
 
c
a
n
 
n
e
s
t
 
p
a
n
e
l
s
 
w
i
t
h
b
o
r
d
e
r
s
:
JPanel p1 = new JPanel();
p1.setBorder(new
 
EtchedBorder());
JPanel p2 = new JPanel();
p2.setBorder(new
 
EtchedBorder());
p1.add(p2);
Self 
Check
 
20.17
 
Why do all user-interface components in the 
FontFrame
 
class share the same
listener?
A
n
s
w
e
r
:
 
W
h
e
n
 
a
n
y
 
o
f
 
t
h
e
 
c
o
m
p
o
n
e
n
t
 
s
e
t
t
i
n
g
s
 
i
s
 
c
h
a
n
g
e
d
,
 
t
h
e
p
r
o
g
r
a
m
 
s
i
m
p
l
y
 
q
u
e
r
i
e
s
 
a
l
l
 
o
f
 
t
h
e
m
 
a
n
d
 
u
p
d
a
t
e
s
 
t
h
e
 
l
a
b
e
l
.
Self 
Check
 
20.18
 
Why was the combo box placed inside a panel? What would have happened if it
had  been added directly to the control
 
panel?
A
n
s
w
e
r
:
 
T
o
 
k
e
e
p
 
i
t
 
f
r
o
m
 
g
r
o
w
i
n
g
 
t
o
o
 
l
a
r
g
e
.
 
I
t
 
w
o
u
l
d
 
h
a
v
e
 
g
r
o
w
n
t
o
 
t
h
e
 
s
a
m
e
 
w
i
d
t
h
 
a
n
d
 
h
e
i
g
h
t
 
a
s
 
t
h
e
 
t
w
o
 
p
a
n
e
l
s
 
b
e
l
o
w
 
i
t
.
Self 
Check
 
20.19
 
How could the following user interface be
 
improved?
 
 
A
n
s
w
e
r
:
 
I
n
s
t
e
a
d
 
o
f
 
u
s
i
n
g
 
r
a
d
i
o
 
b
u
t
t
o
n
s
 
w
i
t
h
 
t
w
o
 
c
h
o
i
c
e
s
,
 
u
s
e
 
a
c
h
e
c
k
b
o
x
.
undefined
Designing 
a 
User
 
Interface
Make 
a 
sketch 
of 
the 
component 
layout. 
Draw 
all 
the 
buttons,
labels, 
text 
fields, 
and 
borders 
on 
a 
sheet 
of 
graph
 
paper.
Find 
groupings 
of 
adjacent 
components 
with 
the 
same 
layout.
Look 
for 
adjacent 
components 
top 
to 
bottom 
or 
left 
to 
 
right.
Identify 
layouts 
for 
each
 
group:
For horizontal components, use flow
 
layout.
For vertical components, use a grid layout with one
 
column.
Group 
the 
groups
 together:
Look at each group as one
 
blob.
Group the blobs together into larger
 
groups.
undefined
Designing 
a 
User
 
Interface
Write 
the 
code 
to 
generate 
the
 
layout.
JPanel radioButtonPanel = new JPanel();
radioButtonPanel.setLayout(new GridLayout(3, 1));
radioButton.setBorder(new TitledBorder(new EtchedBorder(), "Size"));
radioButtonPanel.add(smallButton);
radioButtonPanel.add(mediumButton);
radioButtonPanel.add(largeButton);
JPanel checkBoxPanel = new JPanel();
checkBoxPanel.setLayout(new GridLayout(2, 1));
checkBoxPanel.add(pepperoniButton());
checkBoxPanel.add(anchoviesButton());
JPanel pricePanel = new
 
JPanel();
// Uses FlowLayout by default
pricePanel.add(new JLabel("Your Price:"));
pricePanel.add(priceTextField);
JPanel centerPanel = new JPanel(); // Uses FlowLayout
centerPanel.add(radioButtonPanel);
centerPanel.add(checkBoxPanel);
// Frame uses BorderLayout by default
add(centerPanel, BorderLayout.CENTER);
add(pricePanel, BorderLayout.SOUTH);
undefined
Use 
a 
GUI
 
Builder
A 
GUI 
builder 
reduces 
the 
tedious
 
work:
Drag and drop components onto a
 
panel.
Customize fonts, colors, text, and so on with a dialog
 
box.
Define event handlers by picking the event to process and provide the
code snippet for the listener
 
method.
Powerful 
layout 
manager 
GroupLayout
 
designed 
to 
be used
by 
GUI
 
builders.
undefined
Use 
a 
GUI
 
Builder
Try 
the 
free 
NetBeans 
development 
environment, 
available
 
from
http://netbeans.org
.
F
i
g
u
r
e
 
1
0
 
A
 
G
U
I
 
B
u
i
l
d
e
r
undefined
M
e
nu
s
A 
frame 
can 
contain 
a 
menu
 
bar
.
Menu bar 
contains
 
menus
.
Menu 
contains 
submenus 
and 
menu
 
items
.
Menu 
items 
can 
be 
added 
to 
each 
menu 
or 
submenu.
First, 
add 
the 
menu 
bar 
to 
the
 
frame:
public class MyFrame extends
 
JFrame
{
public
 
MyFrame()
{
JMenuBar menuBar = new
 
JMenuBar();
setJMenuBar(menuBar);
. .
 
.
}
. .
 
.
}
M
e
nu
s
F
i
g
u
r
e
 
1
1
 
P
u
l
l
-
D
o
w
n
 
M
e
n
u
s
undefined
M
e
nu
s
Add 
menus 
to 
the 
menu
 
bar:
JMenu fileMenu = new
 
JMenu("File");
JMenu fontMenu = new
 
JMenu("Font");
menuBar.add(fileMenu);
menuBar.add(fontMenu);
Add 
menu 
items 
and
 
subitems:
JMenuItem exitItem = new
 
JMenuItem("Exit");
fileMenu.add(exitItem);
JMenu styleMenu = new
 
JMenu("Style");
fontMenu.add(styleMenu); // A
 
submenu
Add 
a 
listener 
to 
each 
menu 
item 
(not 
to 
menus 
or 
menu
 
bar):
ActionListener listener = new
 
ExitItemListener();
exitItem.addActionListener(listener);
undefined
M
e
nu
s
Use a 
separate 
method 
for 
each 
menu 
or 
set 
of 
related
 
menus:
public JMenu
 
createFaceMenu()
{
JMenu menu = new JMenu("Face");
menu.add(createFaceItem("Serif"));
menu.add(createFaceItem("SansSerif"));
menu.add(createFaceItem("Monospaced"));
return
 
menu;
}
undefined
M
e
nu
s
createFaceItem
 
method 
needs 
to 
set 
the 
font 
face:
Set the current face
 
name.
Make the new font from the current face, size, and style, and apply it to
label.
Create 
a 
FaceItemListener
 
class 
to 
listen 
for 
face 
item
name
 
actions:
class FaceItemListener implements
 
ActionListener
{
private String
 
name;
public FaceItemListener(String newName) { name = newName; }
public void actionPerformed(ActionEvent
 
event)
{
faceName = name; // Sets an instance variable of the frame class
setLabelFont();
}
}
Install 
a 
listener 
object 
with 
the 
appropriate
 
name:
public JMenuItem createFaceItem(String
 
name)
{
JMenuItem item = new
 
JMenuItem(name);
ActionListener listener = new FaceItemListener(name);
item.addActionListener(listener);
return
 
item;
}
undefined
M
e
nu
s
Better 
to 
make 
a 
local 
inner 
class 
in 
the
 
createFaceItem
method.
actionPerformed
 
method 
can 
access 
the 
name 
parameter
variable 
directly 
(rather 
than 
passing
 
it).
public JMenuItem createFaceItem(final String
 
name)
// Final variables can be accessed from an inner class
 
method
{
class FaceItemListener implements
 
ActionListener
// A local inner
 
class
{
public void actionPerformed(ActionEvent
 
event)
{
facename = name; // Accesses the local variable name
 
setLabelFont();
}
}
JMenuItem item = new
 
JMenuItem(name);
ActionListener listener = new FaceItemListener(name);
item.addActionListener(listener);
return
 
item;
}
Same 
strategy 
used 
for 
the 
createSizeItem
 
and
createStyleItem
 
methods.
section_4/
FontViewer2.java
1
 
import
 
javax.swing.JFrame;
2
3
 
/**
4
 
This 
program 
uses a 
menu 
to display font
 
effects.
5
 
*/
6
 
public class
 
FontViewer2
7
 
{
8
 
public static void 
main(String[]
 
args)
9
 
{
10
JFrame frame = 
new
 
FontFrame2();
11
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
12
frame.setTitle(
"FontViewer"
);
13
frame.setVisible(
true
);
14
 
}
15
 
}
section_4/
FontFrame2.java
/**
This 
frame 
has a 
menu 
with 
commands 
to 
change 
the font
of a text
 
sample.
*/
public class 
FontFrame2 
extends
 
JFrame
{
private static final int 
FRAME_WIDTH = 
300
;
private static final int 
FRAME_HEIGHT =
 
400
;
private 
JLabel label;
private 
String
 
facename;
private int 
fontstyle;
private int
 
fontsize;
/**
Constructs the
 
frame.
*/
public
 
FontFrame2()
{
//
 
Construct text 
sample
label = 
new 
JLabel(
"Big Java"
);
add(label,
 
BorderLayout.CENTER);
1
import
 
java.awt.BorderLayout;
2
import
 
java.awt.Font;
3
import
 
java.awt.event.ActionEvent;
4
import
 
java.awt.event.ActionListener;
5
import
 
javax.swing.JFrame;
6
import
 
javax.swing.JLabel;
7
import
 
javax.swing.JMenu;
8
import
 
javax.swing.JMenuBar;
9
import
 
javax.swing.JMenuItem;
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
//
 
Construct 
menu
JMenuBar menuBar = 
new
 
JMenuBar();
Self 
Check
 
20.20
 
Why do 
JMenu
 
objects not generate action events?
A
n
s
w
e
r
:
 
W
h
e
n
 
y
o
u
 
o
p
e
n
 
a
 
m
e
n
u
,
 
y
o
u
 
h
a
v
e
 
n
o
t
 
y
e
t
 
m
a
d
e
 
a
s
e
l
e
c
t
i
o
n
.
 
O
n
l
y
 
J
M
e
n
u
I
t
e
m
 
o
b
j
e
c
t
s
 
c
o
r
r
e
s
p
o
n
d
 
t
o
 
s
e
l
e
c
t
i
o
n
s
.
Self 
Check
 
20.21
 
Can you add a menu item directly to the menu bar? Try it out. What
 
happens?
A
n
s
w
e
r
:
 
Y
e
s
,
 
y
o
u
 
c
a
n
J
M
e
n
u
I
t
e
m
 
i
s
 
a
 
s
u
b
c
l
a
s
s
 
o
f
 
J
M
e
n
u
.
T
h
e
 
i
t
e
m
 
s
h
o
w
s
 
u
p
 
o
n
 
t
h
e
 
m
e
n
u
 
b
a
r
.
 
W
h
e
n
 
y
o
u
 
c
l
i
c
k
 
o
n
 
i
t
,
 
i
t
s
l
i
s
t
e
n
e
r
 
i
s
 
c
a
l
l
e
d
.
 
B
u
t
 
t
h
e
 
b
e
h
a
v
i
o
r
 
f
e
e
l
s
 
u
n
n
a
t
u
r
a
l
 
f
o
r
 
a
 
m
e
n
u
b
a
r
 
a
n
d
 
i
s
 
l
i
k
e
l
y
 
t
o
 
c
o
n
f
u
s
e
 
u
s
e
r
s
.
Self 
Check
 
20.22
 
Why is the increment parameter variable in the 
createSizeItem
 
method declared
as
 
final
?
A
n
s
w
e
r
:
 
T
h
e
 
p
a
r
a
m
e
t
e
r
 
v
a
r
i
a
b
l
e
 
i
s
 
a
c
c
e
s
s
e
d
 
i
n
 
a
 
m
e
t
h
o
d
 
o
f
 
a
n
i
n
n
e
r
 
c
l
a
s
s
.
Self 
Check
 
20.23
Why
 
can’t
 
the
 
createFaceItem
 
method
 
simply
 
set
 
the
 
faceName
 
instance
variable, like
 
this:
class FaceItemListener implements
 
ActionListener
{
public void actionPerformed(ActionEvent
 
event)
{
setLabelFont();
}
}
public JMenuItem createFaceItem(String
 
name)
{
JMenuItem item = new
 
JMenuItem(name);
faceName =
 
name;
ActionListener listener = new
 
FaceItemListener();
item.addActionListener(listener);
return
 
item;
}
 
A
n
s
w
e
r
:
 
T
h
e
n
 
t
h
e
 
f
a
c
e
N
a
m
e
 
v
a
r
i
a
b
l
e
 
i
s
 
s
e
t
 
w
h
e
n
 
t
h
e
 
m
e
n
u
i
t
e
m
 
i
s
 
a
d
d
e
d
 
t
o
 
t
h
e
 
m
e
n
u
,
 
n
o
t
 
w
h
e
n
 
t
h
e
 
u
s
e
r
 
s
e
l
e
c
t
s
 
t
h
e
 
m
e
n
u
.
Self 
Check
 
20.24
 
In this program, the font specification (name, size, and style) is stored in
instance  variables. Why was this not necessary in the program of the previous
section?
A
n
s
w
e
r
:
 
I
n
 
t
h
e
 
p
r
e
v
i
o
u
s
 
p
r
o
g
r
a
m
,
 
t
h
e
 
u
s
e
r
-
i
n
t
e
r
f
a
c
e
c
o
m
p
o
n
e
n
t
s
 
e
f
f
e
c
t
i
v
e
l
y
 
s
e
r
v
e
d
 
a
s
 
s
t
o
r
a
g
e
 
f
o
r
 
t
h
e
 
f
o
n
t
s
p
e
c
i
f
i
c
a
t
i
o
n
.
 
T
h
e
i
r
 
c
u
r
r
e
n
t
 
s
e
t
t
i
n
g
s
 
w
e
r
e
 
u
s
e
d
 
t
o
 
c
o
n
s
t
r
u
c
t
 
t
h
e
f
o
n
t
.
 
B
u
t
 
a
 
m
e
n
u
 
d
o
e
s
n
t
 
s
a
v
e
 
s
e
t
t
i
n
g
s
;
 
i
t
 
j
u
s
t
 
g
e
n
e
r
a
t
e
s
 
a
n
a
c
t
i
o
n
.
undefined
Exploring 
the 
Swing
 
Documentation
Consider 
an 
example application: 
Use 
sliders 
to 
set 
colors 
of
red, 
green 
and
 
blue.
Swing 
user-interface 
toolkit 
provides 
a 
large 
set 
of 
components.
How 
do 
you 
know 
if 
there 
is 
a
 
slider?
Buy a book that illustrates all Swing
 
components.
Run the sample Swing application included in the Java Development Kit.
Look at the names of all of the classes that start with J and decide that
JSlider may be a good candidate.
F
i
g
u
r
e
 
1
2
 
A
 
C
o
l
o
r
 
V
i
e
w
e
r
 
w
i
t
h
 
S
l
i
d
e
r
s
undefined
JSlider 
Documentation 
and
 
Use
Now 
ask 
some 
questions 
about
 
JSlider:
How do I construct a
 
JSlider?
How can I get notified when the user has moved it?  How can I
tell to which value the user has set
 
it?
Unfortunately, 
documentation 
for 
JSlider 
is
 
voluminous:
Over 50 methods in the JSlider class.  Over 250
inherited
 
methods.
Some of the method descriptions look downright
 
scary.
Concentrate 
on 
what 
you 
will
 
need:
Constructors.  Event
handling.  Get the
 
value.
SwingSet
 
Demo
F
i
g
u
r
e
 
1
3
 
T
h
e
 
S
w
i
n
g
S
e
t
 
D
e
m
o
undefined
JSlider 
Constructor
 
Choice
We 
want 
a 
slider 
value 
between 
0 
and 
255.
Find 
a 
constructor 
that will 
do 
what 
we 
need:
public
 
JSlider()
Creates 
a 
horizontal 
slider 
with 
the 
range 
0 
to 
100 
and 
an 
initial
value 
of
 
50.
public JSlider(BoundedRangeModel
 
brm)
Creates 
a 
horizontal 
slider 
using the
 
specified
BoundedRangeModel
.
public JSlider(int min, int max, int
 
value)
Creates 
a 
horizontal 
slider 
using the 
specified 
min, 
max, 
and
value.
undefined
JSlider 
Event
 
Handling
Goal: 
Add 
a 
change event 
listener 
to 
each 
slider.
There 
is 
no 
addActionListener
 
method.
Possible
 
option:
public void addChangeListener(ChangeListener
 
l)
Looks 
like 
AddActionListener 
calls
stateChanged(ChangeEvent e)
 
whenever 
the 
user 
adjusts
the
 
slider.
F
i
g
u
r
e
 
1
4
 
A
 
M
y
s
t
e
r
i
o
u
s
 
M
e
t
h
o
d
 
D
e
s
c
r
i
p
t
i
o
n
 
f
r
o
m
 
t
h
e
 
A
P
I
 
D
o
c
u
m
e
n
t
a
t
i
o
n
undefined
JSlider 
Event
 
Handling
So 
the 
plan
 
is:
Setup three sliders and one 
ChangeListener
 
object.
Use 
AddChangeListener
, passing our 
ChangeListener
 
to each
slider.
In the 
stateChanged
 
method, check the values of the colors and repaint
the
 
panel.
F
i
g
u
r
e
 
1
5
 
T
h
e
 
C
o
m
p
o
n
e
n
t
s
 
o
f
 
t
h
e
 
C
o
l
o
r
 
V
i
e
w
e
r
 
F
r
a
m
e
section_5/
ColorViewer.java
1
 
import
 
javax.swing.JFrame;
2
3
 
public class
 
ColorViewer
4
 
{
5
 
public static void 
main(String[]
 
args)
6
 
{
7
JFrame frame = 
new
 
ColorFrame();
8
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
9
frame.setVisible(
true
);
10
 
}
11
 
}
section_5/
ColorFrame.java
public class 
ColorFrame 
extends
 
JFrame
{
private static final int 
FRAME_WIDTH = 
300
;
private static final int 
FRAME_HEIGHT =
 
400
;
private 
JPanel colorPanel;
private 
JSlider redSlider;
private 
JSlider
 
greenSlider;
private 
JSlider
 
blueSlider;
public
 
ColorFrame()
{
colorPanel = 
new
 
JPanel();
add(colorPanel,
 
BorderLayout.CENTER);
createControlPanel();
setSampleColor();
setSize(FRAME_WIDTH,
 
FRAME_HEIGHT);
}
1
import
 
java.awt.BorderLayout;
2
import
 
java.awt.Color;
3
import
 
java.awt.GridLayout;
4
import
 
javax.swing.JFrame;
5
import
 
javax.swing.JLabel;
6
import
 
javax.swing.JPanel;
7
import
 
javax.swing.JSlider;
8
import 
javax.swing.event.ChangeListener;
9
import
 
javax.swing.event.ChangeEvent;
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class 
ColorListener 
implements
 
ChangeListener
{
public void 
stateChanged(ChangeEvent event)
{
setSampleColor();
}
Self 
Check
 
20.25
 
Suppose you want to allow users to pick a color from a color dialog box. Which
 
class
would you use? Look in the API
 
documentation.
A
n
s
w
e
r
:
 
J
C
o
l
o
r
C
h
o
o
s
e
r
.
Self 
Check
 
20.26
 
Why does a slider emit change events and not action
 
events?
A
n
s
w
e
r
:
 
A
c
t
i
o
n
 
e
v
e
n
t
s
 
d
e
s
c
r
i
b
e
 
o
n
e
-
t
i
m
e
 
c
h
a
n
g
e
s
,
 
s
u
c
h
 
a
s
b
u
t
t
o
n
 
c
l
i
c
k
s
.
 
C
h
a
n
g
e
 
e
v
e
n
t
s
 
d
e
s
c
r
i
b
e
 
c
o
n
t
i
n
u
o
u
s
 
c
h
a
n
g
e
s
.
Slide Note
Embed
Share

Learn about designing graphical user interfaces in Java, including layout management, common components like radio buttons and menus, browsing Java documentation effectively, and utilizing inheritance for complex frames. Explore topics such as using layout managers to organize UI components, creating complex layouts by nesting panels, and achieving flexibility in design through inheritance.

  • Java GUI
  • Layout Management
  • User Interface Components
  • Inheritance

Uploaded on Sep 11, 2024 | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. Download presentation by click this link. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

E N D

Presentation Transcript


  1. Chapter 20 Graphical User Interfaces

  2. Chapter Goals To use layout managers to arrange user-interface components in a container To use text components to capture and display text in a graphical application To become familiar with common user-interface components, such as radio buttons, check boxes, and menus To browse the Java documentation effectively

  3. Layout Management Build user interface by adding components into containers. Use a layout manager to place thecomponents. JFrame uses Flow layout bydefault.

  4. Border Layout Components are placed toward areas of a container NORTH, EAST, SOUTH, WEST, or CENTER. Specify one when adding components: panel.setLayout(new BorderLayout()); panel.add(component, BorderLayout.NORTH); Figure 1 Components Expand to Fill Space in the Border Layout

  5. Grid Layout Components are placed in boxes in a simple table arrangement. Specify the size (rows then columns) of the grid. Then add components which will be placed from the upper left, across, thendown. JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new GridLayout(4, 3)); buttonPanel.add(button7); buttonPanel.add(button8); buttonPanel.add(button9); buttonPanel.add(button4); . . . Figure 2 The GridLayout

  6. Achieving Complex Layouts Create complex layouts by nesting panels. Give each panel an appropriate layoutmanager. Panels have invisible borders, so you can use as manypanels as you need to organize components. JPanel keypadPanel = new JPanel(); keypadPanel.setLayout(new BorderLayout()); buttonPanel = new JPanel(); buttonPanel.setLayout(new GridLayout(4, 3)); buttonPanel.add(button7); buttonPanel.add(button8); // . . . keypadPanel.add(buttonPanel, BorderLayout.CENTER); JLabel display = new JLabel("0"); keypadPanel.add(display, BorderLayout.NORTH); Figure 3 Nesting Panels

  7. Using Inheritance Use inheritance for complex frames. Design a subclass ofJFrame: Store components as instancevariables. Initialize them in the constructor of your subclass. Easy to add helper methods to organize code. public class FilledFrame extends JFrame { // Use instance variables for components private JButton button; private JLabel label; private static final int FRAME_WIDTH = 300; private static final int FRAME_HEIGHT = 100; public FilledFrame() { // Now we can use a helper method createComponents(); // It is a good idea to set the size in the frame constructor setSize(FRAME_WIDTH, FRAME_HEIGHT); } private void createComponents() { button = new JButton("Click me!"); label = new JLabel("Hello, World!"); JPanel panel = new JPanel(); panel.add(button); panel.add(label); add(panel); } }

  8. Using Inheritance FillledFrameViewer2 mainmethod: public class FilledFrameViewer2 { public static void main(String[] args) { JFrame frame = new FilledFrame(); frame.setTitle("A frame with two components"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }

  9. Self Check 20.1 What happens if you place two buttons in the northern position of a border layout? Try it out with a small program. Answer: Only the second one is displayed.

  10. Self Check 20.2 How do you add two buttons to the northern position of a frame so that they are shown next to each other? Answer: First add them to a panel, then add the panel to the north end of a frame.

  11. Self Check 20.3 How can you stack three buttons one above the other? Answer: Place them inside a panel with a GridLayoutthat has three rows and one column.

  12. Self Check 20.4 What happens when you place one button in the northern position of a border layout and another in the center position? Try it out with a small program if you aren t sure. Answer: The button in the north stretches horizontally to fill the width of the frame. The height of the northern area is the normal height. The center button fills the remainder of the window.

  13. Self Check 20.5 Some calculators have a double-wide 0 button, as shown below. How can you achieve that? Answer: To get the double-wide button, put it in the south of a panel with border layout whose center has a 3 2 grid layout with the keys 7, 8, 4, 5, 1, 2. Put that panel in the west of another border layout panel whose eastern area has a 4 1 grid layout with the remaining keys.

  14. Self Check 20.6 Why does the FilledFrameViewer2class declare the frame variable to have class JFrame, not FilledFrame? Answer: There was no need to invoke any methods that are specific to FilledFrame. It is always a good idea to use the mostgeneral type when declaringa variable.

  15. Self Check 20.7 How many Java source files are required by the application in Section 20.1.3 when we use inheritance to declare the frame class? Answer: Two: FilledFrameViewer2, FilledFrame.

  16. Self Check 20.8 Why does the createComponents method of FilledFrame call add(panel), whereas the main method of FilledFrameViewer calls frame.add(panel)? Answer: It s an instance method of FilledFrame, so the frame is the implicit parameter.

  17. Common Error 20.1 You add components like buttons or labels: panel.add(button); panel.add(label); panel.add(carComponent); Default size for component is 0 by 0 pixels so car component will not be visible. Use setPreferredSize: carComponent.setPreferredSize(new Dimension(CAR_COMPONENT_WIDTH, CAR_COMPONENT_HEIGHT)); Only needed for painted components.

  18. Processing Text Input Dialog boxes allows for user input. Popping up a separate dialog box for each input is not a natural userinterface. Most graphical programs collect text input through text fields. The JTextField class provides a textfield. Specify the width for the text field. If the user exceeds this width, text will scroll left. final int FIELD_WIDTH = 10; final JTextField rateField = new JTextField(FIELD_WIDTH); Figure 4 An Application with a Text Field

  19. Add a Label anda Button Add a label to describe thefield: JLabel rateLabel = new JLabel("Interest Rate: "); Add a button for user to indicate input is complete. actionPerformed methodcan use getText toget inputas a String. Convert to a numeric value if used for calculations. class AddInterestListener implements ActionListener { public void actionPerformed(ActionEvent event) { double rate = Double.parseDouble(rateField.getText()); double interest = balance * rate / 100; balance = balance + interest; resultLabel.setText("Balance: " + balance); } }

  20. section_2_1/InvestmentFrame2.java 1 2 3 4 5 6 7 8 9 import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; /** A frame that shows the growth of an investment with variable interest. 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 */ public class InvestmentFrame2 extends JFrame { private static final int FRAME_WIDTH = 450; private static final int FRAME_HEIGHT = 100; private static final double DEFAULT_RATE = 5; private static final double INITIAL_BALANCE = 1000; private JLabel rateLabel; private JTextField rateField; private JButton button; private JLabel resultLabel; private double balance; public InvestmentFrame2() { balance = INITIAL_BALANCE; resultLabel = new JLabel("Balance: " + balance); createTextField(); createButton();

  21. Text Areas Create multi-line text areas with a JTextArea object. Set the size in rows and columns. final int ROWS = 10; // Lines of text final int COLUMNS = 30; // Characters in each row JTextArea textArea = new JTextArea(ROWS, COLUMNS); Use the setText method to set the text of atext field or text area. textArea.append(balance + "\n"); Can use the text area for display purposes only. textArea.setEditable(false);

  22. TextComponent Class JTextField and JTextArea are subclasses of JTextComponent. setText and setEditable are declared inthe JTextComponent class. Inherited by JTextField and JTextArea. append method is only declared in JTextArea. Figure 5 A Part of the Hierarchy of Swing User-Interface Components

  23. Scrolling To add scroll bars, use JScrollPane: JScrollPane scrollPane = new JScrollPane(textArea); Figure 6 The Investment Application with a Text Area Inside ScrollBars

  24. section_2_2/InvestmentFrame3.java 1 2 3 4 5 6 7 8 9 import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 /** A frame that shows the growth of an investment with variable interest, using a text area. */ public class InvestmentFrame3 extends JFrame { private static final int FRAME_WIDTH = 400; private static final int FRAME_HEIGHT = 250; private static final int AREA_ROWS = 10; private static final int AREA_COLUMNS = 30; private static final double DEFAULT_RATE = 5; private static final double INITIAL_BALANCE = 1000; private JLabel rateLabel; private JTextField rateField; private JButton button; private JTextArea resultArea; private double balance; public InvestmentFrame3()

  25. Self Check 20.9 What happens if you omit the first JLabelobject in the program of Section 20.2.1? Answer: Then the text field is not labeled, and the user will not know its purpose.

  26. Self Check 20.10 If a text field holds an integer, what expression do you use to read its contents? Answer: Integer.parseInt(textField.getText())

  27. Self Check 20.11 What is the difference between a text field and a text area? Answer: A text field holds a single line of text; a text area holds multiplelines.

  28. Self Check 20.12 Why did the InvestmentFrame3program call resultArea.setEditable(false)? Answer: The text area is intended to display the program output. It does not collect user input.

  29. Self Check 20.13 How would you modify the InvestmentFrame3program if you didn t want to use scroll bars? Answer: Don t construct a JScrollPane but add the resultArea object directly to the panel.

  30. Choices GUI components forselections: Radio Buttons For a small set of mutually exclusive choices. Check Boxes For a binary choice. Combo Boxes For a large set of choices.

  31. Radio Buttons Only one button in a set can be selected. Selecting a button clears previous selection. In an old fashioned radio, pushing down one station button released theothers. Create each buttonindividually. Add all buttons in the set to a ButtonGroup object: JRadioButton smallButton = new JRadioButton("Small"); JRadioButton mediumButton = new JRadioButton("Medium"); JRadioButton largeButton = new JRadioButton("Large"); ButtonGroup group = new ButtonGroup(); group.add(smallButton); group.add(mediumButton); group.add(largeButton); Use isSelected to find out whether a button is selected, like: if (largeButton.isSelected()) { size = LARGE_SIZE; }

  32. Radio Button Panels Use a panel for each set of radiobuttons. The default border for a panel is invisible (no border). You can add a border to a panel to make itvisible. Also add a title. JPanel panel = new JPanel(); panel.add(smallButton); panel.add(mediumButton); panel.add(largeButton); panel.setBorder(new TitledBorder(new EtchedBorder(),"Size"));

  33. User Interface Components Figure 7 A Combo Box, Check Boxes, and Radio Buttons

  34. Check Boxes A check box has two states: checked and unchecked. Use for choices that are not mutually exclusive. For example in Figure 7, text may be Italic, Bold, both or neither. Because check box settings do not exclude each other, you do not need to place a set of check boxes inside a button group. Radio buttons are round and have a black dot when selected. Check boxes are square and have a check mark whenselected. Construct a textbox: JCheckBox italicCheckBox = new JCheckBox("Italic"); Use isSelected to find out whether a check box is selected.

  35. Combo Boxes A combo box is a combination of a list and a text field. Clicking the arrow to the right of the text field opens the list of selections. Use a combo box for a large set ofchoices. Use when radio buttons would take up too much space. It can beeither: Closed (shows one selection). Open, showing multiple selections. It can also beeditable: Type a selection into a blank line. facenameCombo.setEditable();

  36. Adding and Selecting Items Add text items to a combo box that will show in the list: JComboBox facenameCombo = new JComboBox(); facenameCombo.addItem("Serif"); facenameCombo.addItem("SansSerif"); . . . Use the getSelectedItem method to return the selected item (as anObject). Combo boxes can store other objects in addition to strings, so casting to a string may be required: String selectedString = (String) facenameCombo.getSelectedItem(); Figure 8 An Open ComboBox

  37. Handling Input Events Radio buttons, check boxes, and combo boxes generate an ActionEvent when selected. In FontViewer program, listener gets all events. Simply check the state of each component using isSelected and getSelectedItem methods. Then redraw the label with the new font.

  38. Font Vi ewer Figure 9 The Components of the Font Frame

  39. section_3/FontViewer.java 1 2 3 4 5 6 7 8 9 import javax.swing.JFrame; /** This program allows the user to view font effects. */ public class FontViewer { public static void main(String[] args) { JFrame frame = new FontFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setTitle("FontViewer"); frame.setVisible(true); } } 10 11 12 13 14 15

  40. section_3/FontFrame.java 1 2 3 4 5 6 7 8 9 import java.awt.BorderLayout; import java.awt.Font; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.border.EtchedBorder; import javax.swing.border.TitledBorder; 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 /** This frame contains a text sample and a control panel to change the font of the text. */ public class FontFrame extends JFrame { private static final int FRAME_WIDTH = 300; private static final int FRAME_HEIGHT = 400; private JLabel label; private JCheckBox italicCheckBox; private JCheckBox boldCheckBox; private JRadioButton smallButton; private JRadioButton mediumButton; private JRadioButton largeButton; private JComboBox facenameCombo; private ActionListener listener; /** Constructs the frame.

  41. Self Check 20.14 What is the advantage of a JComboBoxover a set of radio buttons? What is the disadvantage? Answer: If you have many options, a set of radio buttons takes up a large area. A combo box can show many options without using up much space. But the user cannot see the options as easily.

  42. Self Check 20.15 What happens when you put two check boxes into a button group? Try it out if you are not sure. Answer: If one of them is checked, the other one is unchecked. You should use radio buttons if that is the behavior you want.

  43. Self Check 20.16 How can you nest two etched borders, like this? Answer: You can t nest borders, but you can nest panels with borders: JPanel p1 = new JPanel(); p1.setBorder(new EtchedBorder()); JPanel p2 = new JPanel(); p2.setBorder(new EtchedBorder()); p1.add(p2);

  44. Self Check 20.17 Why do all user-interface components in the FontFrameclass share the same listener? Answer: When any of the component settings is changed, the program simply queries all of them and updates the label.

  45. Self Check 20.18 Why was the combo box placed inside a panel? What would have happened if it had been added directly to the control panel? Answer: To keep it from growing too large. It would have grown to the same width and height as the two panels below it.

  46. Self Check 20.19 How could the following user interface be improved? Answer: Instead of using radio buttons with two choices, use a checkbox.

  47. Designing a User Interface Make a sketch of the component layout. Draw all the buttons, labels, text fields, and borders on a sheet of graph paper. Find groupings of adjacent components with the same layout. Look for adjacent components top to bottom or left to right. Identify layouts for each group: For horizontal components, use flow layout. For vertical components, use a grid layout with one column. Group the groups together: Look at each group as one blob. Group the blobs together into larger groups.

  48. Designing a User Interface Write the code to generate the layout. JPanel radioButtonPanel = new JPanel(); radioButtonPanel.setLayout(new GridLayout(3, 1)); radioButton.setBorder(new TitledBorder(new EtchedBorder(), "Size")); radioButtonPanel.add(smallButton); radioButtonPanel.add(mediumButton); radioButtonPanel.add(largeButton); JPanel checkBoxPanel = new JPanel(); checkBoxPanel.setLayout(new GridLayout(2, 1)); checkBoxPanel.add(pepperoniButton()); checkBoxPanel.add(anchoviesButton()); JPanel pricePanel = new JPanel(); // Uses FlowLayout by default pricePanel.add(new JLabel("Your Price:")); pricePanel.add(priceTextField); JPanel centerPanel = new JPanel(); // Uses FlowLayout centerPanel.add(radioButtonPanel); centerPanel.add(checkBoxPanel); // Frame uses BorderLayout by default add(centerPanel, BorderLayout.CENTER); add(pricePanel, BorderLayout.SOUTH);

  49. Use a GUI Builder A GUI builder reduces the tediouswork: Drag and drop components onto a panel. Customize fonts, colors, text, and so on with a dialog box. Define event handlers by picking the event to process and provide the code snippet for the listener method. Powerful layout manager GroupLayout designed to be used by GUI builders.

  50. Use a GUI Builder Try the free NetBeans development environment, available from http://netbeans.org. Figure 10 A GUI Builder

More Related Content

giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#