You are on page 1of 29

Advanced Java Programming

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.

Other JFC features are Accessibility


API, Java 2D API, Drag -and-Drop
Drag-and-Drop
Support and Internationalization.

19 May 2005 Advanced Java Programming, Summer 2005 2

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.*

19 May 2005 Advanced Java Programming, Summer 2005 3

Swing vs. AWT


Almost every AWT component has a
corresponding Swing component
with a ‘‘J’
J’ prefix (Button Æ JButton
JButton,,
Panel Æ JPanel ).
JPanel).

19 May 2005 Advanced Java Programming, Summer 2005 4

2
Swing Vs. AWT
Lightweight components, platform
independent.

19 May 2005 Advanced Java Programming, Summer 2005 5

Swing Vs. AWT


The main difference between AWT
and Swing components is that swing
components are implemented with
absolutely no native code.
Swing components aren ’t restricted
aren’t
to the features presented in every
platform and therefore can have
more functionality.
19 May 2005 Advanced Java Programming, Summer 2005 6

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

Swing Vs. AWT


Swing
Swing components do not have to be
rectangular,
rectangular, since
since they
they can
can be
be
transparent.
transparent. Buttons
Buttons for
for example
example can
can be
be
round.
round.
The
The Swing
Swing API
API allows
allows you
you to
to specify
specify
which
which look
look and
and feel
feel to
to use,
use, in
in contrast
contrast to
to
AWT
AWT where
where the
the native
native platform
platform look
look and
and
feel
feel is
is always
always used.

19 May 2005 Advanced Java Programming, Summer 2005 8

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");

// ... Add components to the frame

frame.pack();
frame.setVisible(true);

Adding a component to a frame:


frame.getContentPane().add(label);

Closing a frame:
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

19 May 2005 Advanced Java Programming, Summer 2005 11

JLabel

• A component that displays text.


• Can also display an image.
• Does not react to input events.
• Cannot get the keyboard focus.

JLabel label = new JLabel("Hello World");


frame.getContentPane().add(label);

19 May 2005 Advanced Java Programming, Summer 2005 12

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

The JComponent Class


JComponent Features

•• 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

CDE/Motif look and feel

Windows look and feel

Specifying look and feel


UIManager.setLookAndFeel(
UIManager.getCrossPlatformLookAndFeelClassName());

19 May 2005 Advanced Java Programming, Summer 2005 15

Example 1: Swing Application

Topics:

• Dynamic text.
• Borders.

19 May 2005 Advanced Java Programming, Summer 2005 16

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.

JButton button = new JButton("I'm a Swing button!");


button.setMnemonic('i');
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
numClicks++;
label.setText(labelPrefix + numClicks);
}
});

19 May 2005 Advanced Java Programming, Summer 2005 17

Borders
Every JComponent can have one or
more borders.

Borders are incredibly useful


objects that, while not themselves
components, know how to draw the
edges of Swing components.

19 May 2005 Advanced Java Programming, Summer 2005 18

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

19 May 2005 Advanced Java Programming, Summer 2005 19

Example 2: Celsius Converter

Topics:

•The JTextField component.


•The default button.
•Adding HTML.
•Icons.
19 May 2005 Advanced Java Programming, Summer 2005 20

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);

The argument 5 together with the current font determines the


preferred size of the text field. This argument has no effect on
the amount of characters that can be typed.

Event handler for the “convert”


convert” button:
public void actionPerformed(ActionEvent event) {
int newTemp =
(int)((Double.parseDouble(temprature.getText()))
* 1.8 + 32);
fahrenheitLabel.setText(newTemp + " Fahrenheit");
}

19 May 2005 Advanced Java Programming, Summer 2005 21

The default button


At
At most
most one
one button
button in
in aa top-level container
top-level container can
can
be
be the
the default
default button.
button.
The
The default
default button
button is
is highlighted
highlighted and
and acts
acts
clicked
clicked when
when the
the user
user presses
presses enter.
enter.
Useful
Useful in
in Dialog
Dialog windows.
windows.
The
The default
default button
button is
is set
set in
in the
the following
following wayway
(assuming
(assuming we
we are
are in
in the
the constructor
constructor of
of aa top
top--
level
level container):
container):
getRootPane().setDefaultButton(setButton);

19 May 2005 Advanced Java Programming, Summer 2005 22

11
Adding HTML
To add HTML to a component, use the
<html>…</html> tag. HTML is useful
for controlling fonts, colors, line
breaks, etc.

if (tempFahr <= 32) {


fahrenheitLabel.setText("<html><font color=blue>" + tempFahr
+ "&#176 Fahrenheit </font></html>");
} else {
fahrenheitLabel.setText("<html><font color=red>" + tempFahr
+ "&#176 Fahrenheit </font></html>");
}

19 May 2005 Advanced Java Programming, Summer 2005 23

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.

The following code adds the arrow


icon to the ““convert”
convert” button:
ImageIcon icon = new ImageIcon("images/convert.gif",
"Convert temperature");
JButton convertButton = new JButton(icon);

19 May 2005 Advanced Java Programming, Summer 2005 25

Example 3: Lunar Phases

•The JPanel component.


•Compound borders.
•The JComboBox component.
•Using multiple images.

19 May 2005 Advanced Java Programming, Summer 2005 26

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:

selectPanel = new JPanel();


displayPanel = new JPanel();
mainPanel = new JPanel();
mainPanel.setLayout(new GridLayout(2,1,5,5));
mainPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
mainPanel.add(selectPanel); // using the default FlowLayout
mainPanel.add(displayPanel);

19 May 2005 Advanced Java Programming, Summer 2005 27

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)));

The titled border adds a title and a border line


to the component.
The empty border in this case adds a space
between the titled border and the inner
components.
19 May 2005 Advanced Java Programming, Summer 2005 28

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);

An event handler for ActionEvents fired from a combo


box.
public void actionPerformed(ActionEvent event) {
if ("comboBoxChanged".
equals(event.getActionCommand()))
phaseIconLabel.setIcon(
images[phaseChoices.getSelectedIndex()]);
}
}

19 May 2005 Advanced Java Programming, Summer 2005 30

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”).

19 May 2005 Advanced Java Programming, Summer 2005 31

Loading Images
The
The following
following code
code loads
loads the
the images
images in
in advance:
advance:
ImageIcon[] images = new ImageIcon[NUM_IMAGES];

for (int i = 0; i < NUM_IMAGES; i++) {


String imageName = "images/image" + i + ".jpg";
URL iconURL = ClassLoader.getSystemResource(imageName);
images[i] = new ImageIcon(iconURL);
}

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] = new JRadioButton("<html>Candidate 1:


<font color=red>Sparky the Dog</font></html>");
radioButtons[0].setActionCommand(CANDIDATE1_STRING);

radioButtons[1] = new JRadioButton("<html>Candidate 2:


<font color=green>Shady Sadie</font></html>");
radioButtons[1].setActionCommand(CANDIDATE2_STRING);
...
for (int i = 0; i < numButtons; i++)
group.add(radioButtons[i]);

radioButtons[0].setSelected(true);

19 May 2005 Advanced Java Programming, Summer 2005 35

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.

19 May 2005 Advanced Java Programming, Summer 2005 37

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 May 2005 Advanced Java Programming, Summer 2005 38

19
showOptionDialog
Displays
Displays aa modal
modal dialog
dialog with
with specified
specified buttons,
buttons,
title,
title, text
text and
and icon.
icon.

Object[] options = {"Yes!", "No, I'll pass", "Well, if I must"};


int n = JOptionPane.showOptionDialog(
frame, // the owner frame
"Duke is a cartoon mascot... \n“, // message text
"A Follow-up Question", // title
JOptionPane.YES_NO_CANCEL_OPTION, // button format
JOptionPane.QUESTION_MESSAGE, // message type
null, // custom icon
options, // button names
options[2]); // default selection

19 May 2005 Advanced Java Programming, Summer 2005 39

User input from a dialog


The showMessageDialog and
The showMessageDialog showOptionDialog methods
and showOptionDialog methods
both
both return
return an
an integer
integer indicating
indicating the
the user’
user’s choice.
user’s choice.
The
The possible
possible returned
returned values
values are:
are:
•• YES_OPTION
YES_OPTION
•• NO_OPTION
NO_OPTION
•• CANCEL_OPTION
CANCEL_OPTION
•• OK_OPTION
OK_OPTION
•• CLOSED_OPTION
CLOSED_OPTION (dialog
(dialog closed
closed without
without clicking
clicking aa button)
button)

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

Split pane Tabbed pane Tool bar

19 May 2005 Advanced Java Programming, Summer 2005 42

21
Special-purpose containers

Internal frame Layered pane

19 May 2005 Advanced Java Programming, Summer 2005 43

The Root pane


Root
Root pane:
pane:
•• Created
Created automatically
automatically by
by every
every top-
top-level (and
top-level (and internal)
internal) container.
container.
•• Contains
Contains aa Layered
Layered pane.
pane.
Layered
Layered pane:
pane:
•• Holds
Holds components
components in in aa specified
specified depth
depth order.
order.
•• Initially
Initially contains
contains the
the Content
Content pane
pane and
and the
the optional
optional Menu
Menu bar.
bar.
Content
Content pane:
pane:
•• Contains
Contains all
all the
the Root
Root pane’
pane’s visible
pane’s visible components
components (excluding
(excluding the
the Menu
Menu
bar).
bar).
Glass
Glass pane:
pane:
•• A
A hidden
hidden panel
panel that
that intercepts
intercepts input
input events
events for
for the
the Root
Root pane.
pane.
•• Can
Can be
be made
made visible
visible and
and drawn
drawn onon by
by implementing
implementing its its paint()
paint()
method.
method.

19 May 2005 Advanced Java Programming, Summer 2005 44

22
Basic controls
Buttons Combo box List

Menu Slider Text fields

19 May 2005 Advanced Java Programming, Summer 2005 45

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.

19 May 2005 Advanced Java Programming, Summer 2005 46

23
Menus

19 May 2005 Advanced Java Programming, Summer 2005 47

Text components

19 May 2005 Advanced Java Programming, Summer 2005 48

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.

19 May 2005 Advanced Java Programming, Summer 2005 49

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

Label Progress bar Tool tip

19 May 2005 Advanced Java Programming, Summer 2005 51

Editable displays of formatted


information
Color chooser File chooser

Table Tree

19 May 2005 Advanced Java Programming, Summer 2005 52

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

•Clicking a mouse button while the cursor


MouseListener
is over a component

•Moving the mouse over a component MouseMotionListener


•Component becomes visible ComponentListener
•Component gets the keyboard focus FocusListener
•Table or list selection changes ListSelectionListener

19 May 2005 Advanced Java Programming, Summer 2005 53

Converting AWT to Swing


java.awt.*
java.awt.* Æ
••java.awt.* Æ javax.swing.*
javax.swing.*
javax.swing.*
••in
in applets,
applets, change
change java.applet.Applet Æ JApplet.
java.applet.Applet Æ JApplet..
JApplet
••Replace
Replace components
components (e.g.
(e.g. Button Æ JButton).
Button Æ JButton).
JButton).
frame.add(
frame.add(…) Æ
••frame.add(…) Æ frame.getContentPane().add(
frame.getContentPane().add (…).
frame.getContentPane().add(…).
••The
The same
same for
for setLayout(
setLayout(…).
setLayout(…).
••Put
Put custom
custom painting
painting code
code in
in paintComponent(
paintComponent
paintComponent(…) (…) instead
instead
of
of paint()
paint() and
and update().
update().
••Custom
Custom painting
painting in
in aa top-
top-level container
top-level container is
is not
not visible
visible in
in
Swing
Swing (the
(the painting
painting is
is hidden
hidden byby the
the content
content pane).
pane).
Transfer
Transfer the
the painting
painting toto another
another component.
component.
••Thread
Thread safety
safety issues:
issues: AWT
AWT isis thread
thread safety,
safety, while
while Swing
Swing
is
is not.
not.

19 May 2005 Advanced Java Programming, Summer 2005 54

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.

19 May 2005 Advanced Java Programming, Summer 2005 55

Thread safety: the problems


Swing GUI components are updated
in an event dispatching mechanism

In Swing, once a component is


created, it can be updated only
through the event dispatching
mechanism.

Problem 1: What happens if we want to


update the GUI from another thread?
19 May 2005 Advanced Java Programming, Summer 2005 56

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.

19 May 2005 Advanced Java Programming, Summer 2005 57

Thread safety: the solution


The SwingUtilities class
The SwingUtilities class provides
provides two
two
methods that solve the problems:
invokeLater:: this
•• invokeLater this method
method adds
adds some
some
code
code to
to the
the event
event dispatching
dispatching queue.
queue. This
This
code will be executed in its turn. The code
code will be executed in its turn. The code
is
is defined
defined in
in aa Runnable object.
object.

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.

19 May 2005 Advanced Java Programming, Summer 2005 58

29

You might also like