You need the following to make a color-coded JSpinner
:
A
ChangeListener
for theJSpinner
to update the colors when the component value changesA translation of the
String
value into a Color.
There is only one JTextField
used in the spinner so it must be updated with current color on every change event.
spinner.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
try {
String colorString = (String)spinner.getValue();
Field field = Class.forName("java.awt.Color").getField(colorString.toLowerCase()); // toLowerCase because the color fields are RED or red, not Red
Color color = (Color)field.get(null);
JTextField tf = ((JSpinner.DefaultEditor) spinner.getEditor()).getTextField();
tf.setForeground(color);
} catch (Exception ex) { // handle ex }
}
});