| |
14. 33. 29. Customizing the Editor in a JSpinner Component: Create a color spinner |
|
import java.awt.Color;
import java.awt.Dimension;
import java.lang.reflect.Field;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerListModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class Main {
public static void main(String[] argv) throws Exception {
ColorSpinner spinner = new ColorSpinner(new String[] { "red", "green","blue" });
spinner.setValue("blue");
}
}
class ColorSpinner extends JSpinner {
public ColorSpinner(String[] colorNames) {
super();
setModel(new SpinnerListModel(colorNames));
setEditor(new Editor(this));
}
public class Editor extends JPanel implements ChangeListener {
int preferredWidth = 30;
int preferredHeight = 16;
Editor(JSpinner spinner) {
spinner.addChangeListener(this);
setPreferredSize(new Dimension(preferredWidth, preferredHeight));
setColor((String) spinner.getValue());
}
public void stateChanged(ChangeEvent evt) {
JSpinner spinner = (JSpinner) evt.getSource();
String value = (String) spinner.getValue();
setColor(value);
}
public void setColor(String colorName) {
try {
Field field = Class.forName("java.awt.Color").getField(colorName);
Color color = (Color) field.get(null);
setBackground(color);
} catch (Exception e) {
}
}
}
}
|
|
|