Java Reference
In-Depth Information
parse the contents of the text field as a string to the proper data type, then do that. But, if you
want to restrict the input in any manner (for example, allow only numeric input) or provide a
better input mechanism, you must provide your own editor. The interface that defines the
necessary behavior is called ComboBoxEditor and its definition is shown here.
public interface ComboBoxEditor {
// Properties
public Component getEditorComponent();
public Object getItem();
public void setItem(Object anObject);
// Listeners
public void addActionListener(ActionListener l);
public void removeActionListener(ActionListener l);
// Other methods
public void selectAll();
}
Note The default editor is the BasicComboBoxEditor implementation in the javax.swing.plaf.basic
package.
The add / remove listener methods are necessary for notifying any listeners when the
ComboBoxEditor value has changed. It's not necessary for you to add a listener, and normally
you won't do that. Nevertheless, the methods are part of the interface, so they'll need to be
implemented if you want to provide your own editor.
The getEditorComponent() method returns the Component object used for the editor. You
can use either an AWT or a Swing component for the editor (for example, a JColorChooser for
color selection). The selectAll() method is called when the editor is first shown. It tells the
editor to select everything within it. Selecting everything allows a user to merely type over the
current input for the default JTextField case. Some editors may not require use of this method.
The item property methods demand the most work when you're providing a custom
editor. You'll need to supply a method to map the specific pieces of the Object subclass to the
components in order to present the data to be edited. You then need to get the data from the
editor so that the data can be stored back in an instance of the original object.
To demonstrate, the source code in Listing 13-14 is a ComboBoxEditor for the Color class.
A custom editor is necessary because there's no automatic way to parse the results of editing
the default string shown for a Color . This editor will use a JColorChooser for the user to pick
a new color value. The getItem() method needs to return only the current value, a Color .
The setItem() method needs to convert the object passed to a Color object; the argument to
setItem() is an Object . The setItem() method could be made to accept only Color arguments.
However, for this example, any string that's decodable with the Color.decode() method is also
supported.
 
Search WWH ::




Custom Search