Customizing the Editor in a JSpinner Component: Create a color spinner : Spinner « Swing JFC « Java

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" });
class ColorSpinner extends JSpinner {
  public ColorSpinner(String[] colorNames) {
    setModel(new SpinnerListModel(colorNames));
    setEditor(new Editor(this));

  public class Editor extends JPanel implements ChangeListener {
    int preferredWidth = 30;
    int preferredHeight = 16;

    Editor(JSpinner spinner) {
      setPreferredSize(new Dimension(preferredWidth, preferredHeight));
      setColor((String) spinner.getValue());
    public void stateChanged(ChangeEvent evt) {
      JSpinner spinner = (JSpinner) evt.getSource();

      String value = (String) spinner.getValue();


    public void setColor(String colorName) {
      try {
        Field field = Class.forName("java.awt.Color").getField(colorName);
        Color color = (Color) field.get(null);
      } catch (Exception e) {


Related examples in the same category

1.A program to test spinners.A program to test spinners.
2.An implementation of JSpinner with customized content--iconsAn implementation of JSpinner with customized content--icons
3.A quick test of various spinnersA quick test of various spinners
4.An example of JSpinner with a custom editorAn example of JSpinner with a custom editor
5.Create a spinnerCreate a spinner
6.Demonstrating the JSpinner ComponentDemonstrating the JSpinner Component
7.Demonstrate the Swing Spinner control
8.Spinner 2Spinner 2
9.Listening for Changes to the Value in a JSpinner Component
10.Creating a SpinnerListModel That Loops Through Its Values
11.Setting the Margin Space on a JSpinner Component
12.Limiting the Values in a Number JSpinner Component
13.Disabling Keyboard Editing in a JSpinner Component
14.Creating an Hour JSpinner Component
15.Creating a JSpinner Component: A number spinner:
16.A list spinner
17.A date spinner
18.A spinner of dates
19.Use an Icon Editor for use with the JSpinner component
20.Use images in tooltips
21.Number spinner
22.Date spinner
23.List based spinner
24.Java Spinner ComponentJava Spinner Component
25.Enhanced Spinner List Formatter
26.Enhanced Spinner List Model