Java Swing How to - Create custom model for JSpinner








Question

We would like to know how to create custom model for JSpinner.

Answer

//from  ww w. ja v a2s.  c o m
import java.awt.BorderLayout;
import java.util.List;

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


class RolloverSpinnerListModel extends SpinnerListModel {

  public RolloverSpinnerListModel(List<?> values) {
    super(values);
  }

  public RolloverSpinnerListModel(Object[] values) {
    super(values);
  }
  public Object getNextValue() {
    Object returnValue = super.getNextValue();
    if (returnValue == null) {
      returnValue = getList().get(0);
    }
    return returnValue;
  }

  public Object getPreviousValue() {
    Object returnValue = super.getPreviousValue();
    if (returnValue == null) {
      List list = getList();
      returnValue = list.get(list.size() - 1);
    }
    return returnValue;
  }
}
public class Main {
  public static void main(String args[]) {
    JFrame frame = new JFrame("JSpinner Sample");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    String[] values = new String[]{"a","b","c"};
    
    RolloverSpinnerListModel model = new RolloverSpinnerListModel(values);
    
    JSpinner spinner1 = new JSpinner(model);

    JPanel panel1 = new JPanel(new BorderLayout());
    panel1.add(spinner1, BorderLayout.CENTER);
    frame.add(panel1, BorderLayout.SOUTH);

 

    frame.setSize(200, 90);
    frame.setVisible(true);
  }
}