Java JSpinner extend to create custom spinner
import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.lang.reflect.Field; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JSpinner; import javax.swing.SpinnerListModel; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; class ColorSpinner extends JSpinner { public ColorSpinner(String[] colorNames) { super();//from w w w . j av a 2s . c o m 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) { } } } } public class Main extends JFrame { public Main() { super("java2s.com"); setDefaultCloseOperation(EXIT_ON_CLOSE); setLayout(new FlowLayout()); ColorSpinner spinner = new ColorSpinner(new String[]{"red","blue","black","yellow"}) ; getContentPane().add(spinner); } public static void main(String[] args) { Main frame = new Main(); frame.pack(); frame.setVisible(true); } }