Java Reference
In-Depth Information
There's a special kind of listener for JList selection events that implements the
ListSelectionListener interface. Since we set the FontDialog object as the listener for the list
in the call to the addListSelectionListener() method, we had better make sure the
FontDialog class implements the interface:
class FontDialog extends JDialog
implements Constants, ActionListener, // For buttons etc.
ListSelectionListener { // For list box
There's only one method in the ListSelectionListener interface, and we can implement it like this:
// List selection listener method
public void valueChanged(ListSelectionEvent e) {
if(!e.getValueIsAdjusting()) {
font = new Font((String)fontList.getSelectedValue(), fontStyle, fontSize);
fontDisplay.setFont(font);
fontDisplay.repaint();
}
}
This method is called when you select an item in the list. We have only one list so we don't need to
check which object was the source of the event. If we needed to, we could call the getSource()
method for the event object that is passed to valueChanged() , and compare it with the references to
the JList objects.
The ListSelectionEvent object that is passed to the valueChanged() method contains records
of the index positions of the list items that changed. You can obtain these as a range by calling
getFirstIndex() for the event object for the first in the range, and getLastIndex() for the last.
We don't need to worry about this because we have disallowed multiple selections and we just want the
newly selected item in the list.
We have to be careful though. Since we start out with an item already selected, selecting another font
name from the list will cause two events - one for deselecting the original font name, and the other for
selecting the new name. We make sure we only deal with the last event by calling the
g etValueIsAdjusting() method for the event object in the if expression. This returns false
when all changes due to a selection are complete, and true if things are still changing. Once we are
sure nothing further is changing, we retrieve the selected font name from the list by calling its
getSelectedValue() method. The item is returned as type Object so we have to cast it to type
String before using it. We create a new Font object using the selected family name and the current
values for fontStyle and fontSize . We store the new font in the data member font , and also call
the setFont() member of a data member fontDisplay that we haven't added yet. This will be a
JLabel object displaying a sample of the current font. After we've set the new font, we call
repaint() for the label, fontDisplay , to get it redrawn.
Search WWH ::




Custom Search