Java Reference
In-Depth Information
// Try to decode
try {
Color color = Color.decode(newValue.toString());
editor.setBackground(color);
} catch (NumberFormatException e) {
// Ignore - value unchanged
}
}
}
protected void fireActionEvent(Color color) {
Object listeners[] = listenerList.getListenerList();
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i] == ActionListener.class) {
ActionEvent actionEvent =
new ActionEvent(editor, ActionEvent.ACTION_PERFORMED, color.toString());
((ActionListener)listeners[i+1]).actionPerformed(actionEvent);
}
}
}
}
To use the new editor, you need to associate it with a JComboBox . After you change the
EditComboBox example shown earlier (Listing 13-13) to make the data model consist of an array
of Color objects, you can then install the editor by adding the following:
Color color = (Color)comboBox.getSelectedItem();
ComboBoxEditor editor = new ColorComboBoxEditor(color);
comboBox.setEditor(editor);
A complete test program follows in Listing 13-15. It's different from the EditComboBox
because below the JComboBox is a JLabel that stays in sync with the currently selected color of
the JComboBox . There's also a custom cell renderer that sets the background color to the value
of the cell.
Listing 13-15. Custom JComboBox Editor Sample
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class ColorComboBox {
static class ColorCellRenderer implements ListCellRenderer {
protected DefaultListCellRenderer defaultRenderer =
new DefaultListCellRenderer();
// Width doesn't matter as the combo box will size
private final static Dimension preferredSize = new Dimension(0, 20);
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
JLabel renderer = (JLabel)defaultRenderer.getListCellRendererComponent(
list, value, index, isSelected, cellHasFocus);
Search WWH ::




Custom Search