Academic Java    Java Tutorial  >  Swing  >  JSpinner

JSpinner Example

Java JSpinner EXAMPLE output This JSpinner example allows the user to select between a number of garment sizes. The JSpinner is useful for providing a large number of values from which the user chooses just one.

Only one value is displayed at a time; up and down arrows enable the user to make a selection.

It therefore takes up very little screen space.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// JSpinner and SpinnerList Model Example
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;

class JSpinnerExample {

   public static void main(String[] args) {

      String[] sizes = {"small","medium","large","XL","XXL"};

      final SpinnerListModel model = new SpinnerListModel(sizes);

      JSpinner jSpinner = new JSpinner(model);

      model.addChangeListener(new ChangeListener() {
         public void stateChanged(ChangeEvent e) {
            System.out.println(model.getValue());
         }
      });

      JFrame frame = new JFrame();
      frame.getContentPane().add(jSpinner);
      frame.pack();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
   }
}

12 A SpinnerListModel is constructed from a string array. This is used as a parameter for the JSpinner constructor.

14 The JSpinner constructor takes a SpinnerModel as parameter. In this case a SpinnerListModel. Other possible models are SpinnerDateModel and SpinnerNumberModel.