Java JSpinner create from SpinnerListModel

Description

Java JSpinner create from SpinnerListModel

import javax.swing.JFrame;
import javax.swing.JSpinner;
import javax.swing.SpinnerListModel;
import javax.swing.SpinnerModel;

class CyclingSpinnerListModel extends SpinnerListModel {
  Object firstValue, lastValue;/*from  w w w .j a  va  2 s  .c om*/

  SpinnerModel linkedModel = null;

  public CyclingSpinnerListModel(Object[] values) {
    super(values);
    firstValue = values[0];
    lastValue = values[values.length - 1];
  }

  public void setLinkedModel(SpinnerModel linkedModel) {
    this.linkedModel = linkedModel;
  }

  public Object getNextValue() {
    Object value = super.getNextValue();
    if (value == null) {
      value = firstValue;
      if (linkedModel != null) {
        linkedModel.setValue(linkedModel.getNextValue());
      }
    }
    return value;
  }

  public Object getPreviousValue() {
    Object value = super.getPreviousValue();
    if (value == null) {
      value = lastValue;
      if (linkedModel != null) {
        linkedModel.setValue(linkedModel.getPreviousValue());
      }
    }
    return value;
  }
}

public class Main {

  public static void main(String[] a) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JSpinner spinner = new JSpinner(new CyclingSpinnerListModel(new String[]{"A","B","C"}));
    frame.add(spinner);

    frame.setSize(300, 75);
    frame.setVisible(true);
  }

}



PreviousNext

Related