Beruflich Dokumente
Kultur Dokumente
Swing
Eran Werner,
Tel-Aviv University
Tel-Aviv
Summer, 2005
19 May 2005 Advanced Java Programming, Summer 2005 1
Introduction to Swing
The Swing package is part of the
Java Foundation Classes (JFC), a
group of features for GUI design.
1
Swing libraries
All Swing components are under
javax.swing
javax.swing.*.*
Since Swing uses the AWT event
model, we need to add the following
in order to use events:
•• java.awt .*
java.awt.*
•• Java.awt.event.*
Java.awt.event.*
2
Swing Vs. AWT
Lightweight components, platform
independent.
3
Swing Vs. AWT
Swing Buttons and labels can
display images as well as text.
You can add or change the borders
for swing components.
You can easily change the behavior
or a swing component by
subclassing it or invoking its
methods
19 May 2005 Advanced Java Programming, Summer 2005 7
4
Swing Vs. AWT
Swing components use models to
keep the state. A Jslider uses
BoundedRangeModel
BoundedRangeModel.. A JTable uses
a TableModel
TableModel..
Models are set up automatically so
you don ’t have to bother them
don’t
unless you want to take advantage
of them.
19 May 2005 Advanced Java Programming, Summer 2005 9
Top-level container
Every
Every program
program with
with aa Swing
Swing GUI
GUI must
must
have
have at
at least
least one
one top-level container.
top-level container.
There
There are
are three
three top -level containers:
top-level containers:
JFrame:: aa main
•• JFrame main window
window
JDialog:: aa secondary
•• JDialog secondary window,
window, dependent
dependent
on
on another
another window.
window.
JApplet:: An
•• JApplet An applet
applet display
display area
area within
within aa
browser
browser window.
window.
19 May 2005 Advanced Java Programming, Summer 2005 10
5
JFrame
Setting
Setting up
up aa frame:
frame:
JFrame frame = new JFrame("HelloWorldSwing");
frame.pack();
frame.setVisible(true);
Closing a frame:
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel
6
The JComponent Class
All Swing components whose names
begin with "J" descend from the
JComponent (except JFrame and JDialog
– top level containers) .
For example,
example, JPanel
JPanel,, JScrollPane
JScrollPane,,
JButton
JButton,, and JTable
JTable..
JComponent extends java.awt.Container
java.awt.Container
19 May 2005 Advanced Java Programming, Summer 2005 13
•• Tool
Tool tips
tips
•• Painting
Painting and
and borders
borders
•• Application -wide pluggable
Application-wide pluggable look
look and
and feel
feel
•• Support
Support for
for drag
drag and
and drop
drop
•• Double
Double buffering
buffering
•• Key
Key bindings
bindings
19 May 2005 Advanced Java Programming, Summer 2005 14
7
Look and Feel
Java (cross-
(cross-platform) look and feel
Topics:
• Dynamic text.
• Borders.
8
Dynamic text
Creating a button
• The mnemonic functions as a hot key.
• The event handler updates the label’
label’s text when the button is clicked.
Borders
Every JComponent can have one or
more borders.
9
Borders
To put a border around a
JComponent
JComponent,, you use its setBorder
method. You can use the
BorderFactory class to create most of
the borders that Swing provides.
panel.setBorder
(BorderFactory.createEmptyBorder(30, //top
30, //left
10, //bottom
30)); //right
Topics:
10
JTextField
Allows the editing of a single line of text.
Fires TextEvents
TextEvents when changed (notifies a TextListener).
TextListener).
JTextField temprature = new JTextField(5);
11
Adding HTML
To add HTML to a component, use the
<html>…</html> tag. HTML is useful
for controlling fonts, colors, line
breaks, etc.
Icons
An icon usually refers to a
descriptive fixed -size image.
fixed-size
Some components can be decorated
with an icon.
Swing provides an interface called
Icon.
It also provides a useful
implementation of this interface:
ImageIcon..
ImageIcon
19 May 2005 Advanced Java Programming, Summer 2005 24
12
Icons
ImageIcon constructs an icon from
a GIF or JPEG image.
13
JPanel
A
A general-
general -purpose container
general-purpose container (without
(without aa window).
window).
A
A panel
panel is
is opaque
opaque by
by default.
default.
To
To make
make it
it transparent,
transparent, use
use setOpaque(false).
setOpaque(false
setOpaque(false). ).
A
A transparent
transparent panel
panel has
has no
no background
background (components
(components under
under it
it
show
show through).
through).
The
The Lunar
Lunar Phase
Phase example
example uses
uses several
several panels:
panels:
Compound borders
It
It is
is possible
possible to
to set
set more
more than
than one
one border
border to
to aa
component.
component. we we can
can specify
specify an
an outer
outer and
and inner
inner borders
borders
by
by BorderFactory.createCompoundBorder
BorderFactory.createCompoundBorder
selectPanel.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder("Select Phase"),
BorderFactory.createEmptyBorder(5,5,5,5)));
14
JComboBox
A
A component
component that
that enables
enables user
user choice.
choice.
Can
Can bebe editable
editable allowing
allowing toto dynamically
dynamically
add choices.
add choices.
Constructed
Constructed with
with an
an array
array of
of Strings.
Strings. Icons
Icons
can
can also
also be
be added.
added.
An
An initial
initial item
item can
can be
be selected
selected using
using the
the
setSelectedIndex method.
setSelectedIndex method.
The
The selection
selection is
is done
done by
by the
the item
item index.
index.
When
When thethe user
user starts
starts writing
writing anan item
item the
the
selection
selection changes
changes accordingly.
accordingly.
19 May 2005 Advanced Java Programming, Summer 2005 29
JComboBox
String[] phases = { "New", "Waxing Crescent“,
"First Quarter", "Waxing Gibbous",
"Full", "Waning Gibbous",
"Third Quarter", "Waning Crescent“
};
JComboBox phaseChoices = new JComboBox(phases);
phaseChoices.setSelectedIndex(START_INDEX);
15
Using multiple images
In the Lunar Phase example, we have
a ““bank”
bank” of 8 images, but display
only one at a time.
We can choose whether to load all
images in advance, or to load a single
image when it is required ((“lazy
“lazy
image loading”).
loading”).
Loading Images
The
The following
following code
code loads
loads the
the images
images in
in advance:
advance:
ImageIcon[] images = new ImageIcon[NUM_IMAGES];
ClassLoader.getSystemResource(imageName)
ClassLoader.getSystemResource(imageName
ClassLoader.getSystemResource(imageName) )
searches
searches for
for the
the image
image file
file in
in the
the classpath.
classpath..
classpath
A
A URL
URL object
object with
with the
the file’
file’s location
file’s location is
is returned.
returned.
This
This way,
way, we
we don’
don’t have
don’t have to
to specify
specify the
the full
full path
path of
of the
the
images.
images.
19 May 2005 Advanced Java Programming, Summer 2005 32
16
Example 4: Vote Dialog
Topics:
• The JRadioButton
component.
• Dialogs.
– Displaying and
customizing dialogs.
– Receiving user input
from a dialog.
19 May 2005 Advanced Java Programming, Summer 2005 33
JRadioButton
An item that can be selected or
deselected.
For each group of radio buttons, you
need to create a ButtonGroup
instance and add each radio button to
it.
ButtonGroup takes care of
unselecting the previously selected
button when the user selects another
one in the group.
19 May 2005 Advanced Java Programming, Summer 2005 34
17
JRadioButton
JRadioButton[] radioButtons = new JRadioButton[numButtons];
ButtonGroup group = new ButtonGroup();
radioButtons[0].setSelected(true);
Dialogs
AA top -level window
top-level window with
with aa title
title and
and aa border.
border.
used to get some input from the user.
used to get some input from the user.
Must
Must have
have aa frame
frame or
or another
another dialog
dialog as
as its
its
““owner”.
owner”.
•• When
When the
the owner
owner is
is destroyed,
destroyed, so
so is
is the
the dialog.
dialog.
•• When
When the
the owner
owner is
is minimized,
minimized, so
so is
is the
the dialog.
dialog.
Can
Can be
be modal
modal (disables
(disables all
all input
input to
to other
other top
top--
level
level windows).
windows).
Can
Can be
be used
used to
to create
create aa custom
custom dialog
dialog (many
(many
ready
ready made
made dialogs
dialogs are
are available
available in
in
JOptionPane
JOptionPane).).
19 May 2005 Advanced Java Programming, Summer 2005 36
18
JOptionPane
Enables creation and customization of
several kinds of modal dialogs.
Dialogs are created by invoking one of
the static creation methods in
JOptionPane
Customization options:
•• Choosing
Choosing anan icon.
icon.
•• Setting
Setting the
the title
title and
and text.
text.
•• Setting
Setting the
the button
button text.
text.
showMessageDialog
Displays
Displays aa modal
modal dialog
dialog with
with one
one button
button
labeled
labeled ““ok”.
ok”.
The
The title,
title, text
text and
and icon
icon are
are customizable.
customizable.
JOptionPane.showMessageDialog
(frame,"This candidate is a dog. " + "Invalid vote.");
19
showOptionDialog
Displays
Displays aa modal
modal dialog
dialog with
with specified
specified buttons,
buttons,
title,
title, text
text and
and icon.
icon.
The
The value
value is
is returned
returned according
according to
to the
the clicked
clicked button
button and
and the
the
button format of the dialog (DEFAULT, YES_NO,
button format of the dialog (DEFAULT, YES_NO,
YES_NO_CANCEL,
YES_NO_CANCEL, OK). OK).
The
The buttons’
buttons’’ text
buttons text doesn’
doesn’t affect
doesn’t affect the
the returned
returned value.
value.
19 May 2005 Advanced Java Programming, Summer 2005 40
20
Swing components
The rest of this presentation
contains a short description of most
Swing components:
•• General -purpose containers.
General-purpose containers.
•• Special -purpose containers.
Special-purpose containers.
•• Basic
Basic controls.
controls.
•• Uneditable
Uneditable information
information displays.
displays.
•• Editable
Editable displays
displays of
of formatted
formatted information.
information.
19 May 2005 Advanced Java Programming, Summer 2005 41
General-purpose containers
Panel Scroll pane
21
Special-purpose containers
22
Basic controls
Buttons Combo box List
Buttons
The
The following
following list
list contains
contains all
all button
button types
types (all
(all
are
are subclasses
subclasses of AbstractButton):
of AbstractButton ):
JButton:: aa common
•• JButton:
JButton common button.
button.
JCheckBox:: aa check
•• JCheckBox:
JCheckBox check box
box button.
button.
JRadioButton:: one
•• JRadioButton:
JRadioButton one of
of aa group
group of
of radio
radio buttons.
buttons.
JMenuItem:: an
•• JMenuItem:
JMenuItem an item
item in
in aa menu.
menu.
JCheckBoxMenuItem:: aa menu
•• JCheckBoxMenuItem:
JCheckBoxMenuItem menu item
item that
that has
has aa check
check box.
box.
JRadioButtonMenuItem:: aa menu
•• JRadioButtonMenuItem:
JRadioButtonMenuItem menu item
item that
that has
has aa radio
radio
button.
button.
JToggleButton:: aa two-
•• JToggleButton:
JToggleButton two-state button.
two-state button.
23
Menus
Text components
24
Documents
All
All Swing
Swing components
components separate
separate their
their data
data (or
(or
model)
model) from
from the
the view
view of
of the
the data.
data.
Text
Text components
components use
use aa Document
Document as
as their
their
model:
model:
•• Contains
Contains the
the text
text itself
itself
(including
(including style
style info).
info).
•• Provides
Provides support
support for
for editing
editing
the
the text.
text.
•• Notifies
Notifies document
document listeners
listeners
on changes to the text.
on changes to the text.
Editor kits
Each
Each text
text component
component holds
holds an
an editor
editor kit:
kit:
•• Manages
Manages editing
editing actions
actions (cut,
(cut, paste,
paste, etc)
etc) for
for the
the text
text
component.
component.
•• Reads
Reads and
and writes
writes documents
documents of of aa particular
particular format.
format.
DefaultEditorKit:
DefaultEditorKit:
DefaultEditorKit:
•• Reads
Reads and
and writes
writes plain
plain text.
text.
•• Provides
Provides a basic set of editing commands.
a basic set of editing commands.
•• The
The super
super class
class of
of all
all other
other editor
editor kits.
kits.
StyledEditorKit:
StyledEditorKit:
StyledEditorKit:
•• Reads
Reads and
and writes
writes styled
styled text.
text.
•• Provides
Provides editing commands for
editing commands for styled
styled text.
text.
HTMLEditorKit:
HTMLEditorKit:
HTMLEditorKit:
•• Reads,
Reads, writes
writes and
and edits
edits HTML.
HTML.
•• Subclass
Subclass of
of StyledEditorKit.
StyledEditorKit
StyledEditorKit. .
19 May 2005 Advanced Java Programming, Summer 2005 50
25
Uneditable information
displays
Table Tree
26
GUI events
Examples of Events and Their Associated Event Listeners
Action that Results in the Event Listener Type
•Clicking a button
•Pressing enter while typing in a text field ActionListener
•Choosing a menu item
•Closing a frame (main window) WindowListener
27
Converting AWT to Swing
The containment hierarchy for any
window or applet containing swing
components must have a swing top
level container at the root of the
hierarchy. For example the main
window should be a JFrame rather
than a Frame.
28
Thread safety: the problems
Problem2:
Problem2: when
when aa button
button is
is clicked,
clicked, the
the
following
following actions
actions occur
occur one
one after
after the
the other:
other:
•• The
The button’
button’s GUI
button’s GUI is
is drawn
drawn as
as ‘‘pressed’
pressed’
pressed’
•• The button’
button’s listeners are notified on
The button’s listeners are notified on the
the press.
press.
•• The
The button’
button’s GUI
button’s GUI is
is drawn
drawn as
as ‘‘released’
released’
released’
Suppose
Suppose that
that one
one of
of the
the listeners
listeners changes
changes
the
the appearance
appearance of
of the
the button.
button.
When
When all
all listeners
listeners finished,
finished, the
the button
button is
is
redrawn (as ‘ released ’ ) and the appearance
redrawn (as ‘released’) and the appearance
changes
changes may
may be be erased.
erased.
invokeAndWait:: like
•• invokeAndWait like invokeLater
invokeLater,, but
but
this
this method
method waits
waits for
for the
the code
code to
to be
be
executed,
executed, and
and only
only then
then it
it returns.
returns.
29