Create a custom model by extending SpinnerListModel for JSpinner in Java

Description

The following code shows how to create a custom model by extending SpinnerListModel for JSpinner.

Example


//  ww w . j  a  v  a 2  s .co 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[]{"java2s.com","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);
  }
}

The code above generates the following result.

Create a custom model by extending SpinnerListModel for JSpinner in Java




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer