Java Reference
In-Depth Information
// List selection listener method
public void valueChanged(ListSelectionEvent e) {
if(!e.getValueIsAdjusting()) {
font = new Font(fontList.getSelectedValue(),
font.getStyle(), font.getSize());
fontDisplay.setFont(font);
fontDisplay.repaint();
}
}
Directory "Sketcher 5 displaying a font dialog"
This method is called when you select an item in the list. You have only one list, so you don't need to
check which object was the source of the event. If you were handling events from several lists, you could
call the
getSource()
method for the event object that is passed to
valueChanged(
), and compare it with
the references to the
JList<>
objects being used.
The
ListSelectionEvent
object that is passed to the
valueChanged()
method contains the index posi-
tions of the list items that changed. You can obtain these as a range by calling the
getFirstIndex()
method
for the event object to get the first in the range, and the
getLastIndex()
method returns the last. You don't
need to worry about any of this in the
FontDialog
class. Because you have disallowed multiple selections,
you only get one index.
You have to be careful, though. Because you start out with an item already selected, selecting another
font name from the list causes two events — one for deselecting the original font name and the other for se-
lecting the new name. To make sure that you deal only with the last event, you call the
getValueIsAdjust-
ing()
method for the event object in the
if
expression. This returns
false
for the event when all changes
due to a selection are complete, and
true
if things are still changing when the event occurred. Thus your
implementation of the
valueChanged()
method does nothing when the
getValueIsAdjusting()
method
returns
true
.
You are sure nothing further is changing when
getValueIsAdjusting()
returns
false
, so you retrieve
the selected font name from the list by calling its
getSelectedValue()
method. You create a new
Font
ob-
ject using the selected family name and the current values for
fontStyle
and
fontSize
. You store the new
font in the data member
font
and call the
setFont()
member of a data member,
fontDisplay
, that you
haven't added to the
FontDialog
class yet. This is a
JLabel
object displaying a sample of the current font.
After you've set the new font, you call
repaint()
for the
fontDisplay
label to get it redrawn with the new
font.
You need another import statement for the
ListSelectionListener
and
ListSelectionEvent
types:
import javax.swing.event.*;
Displaying the Selected Font
You display the selected font in a
JLabel
object that you place in another
JPanel
pane. Adding the follow-
ing code to the constructor does this: