Java Reference
In-Depth Information
You obtain the list of font family names by calling the
getAvailableFontFamilyNames()
method for
the
GraphicsEnvironment
object. The
fontList
variable needs to be accessible in the method that handles
events for the list, so this is another data member of the
FontDialog
class:
private JList<String> fontList;
// Font list
A
JList<>
component doesn't support scrolling directly, but it is scrolling “aware." To get a scrollable
list with scrollbars, you just pass the
JList<>
object to the
JScrollPane
constructor. A
JScrollPane
object
creates a pane with scrollbars — either vertical, horizontal, or both — as necessary — for whatever it con-
tains. You set a minimum size for the
JScrollPane
object to limit how small it can be made in the split pane
into which you insert it in a moment. Note how easy it is to get the mouse wheel supported for scrolling here.
You just call the
setWheelScrollingEnabled(
) method for the scroll pane with the argument as
true
, and
it's done. You don't really need it here, but just because you can, you set a tooltip for the
fontList
object.
Any component can have a tooltip set.
Working with JList<T> Components
You can create a
JList<>
object by passing an array or a
Vector<>
object that contains the objects you
want in the list to the constructor. The
fontNames
array holds
String
objects, but you can create a
JList<>
object for any kind of object, including images, for example. It is possible to allow multiple entries from a
list to be selected. Calling
setSelectionMode()
with the argument
SINGLE_SELECTION
ensures that only
one font name can be selected.
You have two multiple selection modes that you can enable for a
JList<>
object. Passing the value
SINGLE_INTERVAL_SELECTION
to the
setSelectionMode()
method allows a series of consecutive items
to be selected. Passing
MULTIPLE_SELECTION_INTERVAL
provides you with total flexibility and allows any
number of items anywhere to be selected. The initial selection in the list is set by the
setSelectedValue()
call. You pass the name for the current font as the argument specifying the initial selection. There is a com-
plementary method,
getSelectedValue()
, that you use in the event handler.
Handling JList<T> Component Events
There's a special kind of listener for
JList<>
selection events that is an object of a class type that imple-
ments the
javax.swing.event.ListSelectionListener
interface. You set the
FontDialog
object as the
listener for the list in the call to the
addListSelectionListener()
method, so you had better make sure
the
FontDialog
class implements the interface:
class FontDialog extends JDialog
implements ActionListener,
// For buttons etc.
ListSelectionListener {
// For list box
There's only one method in the
ListSelectionListener
interface, and you can implement it in the
FontDialog
class like this: