Creating Spinner Using JSpinner Class

In this tutorial, we will show you how to use JSpinner class to create spinner widget with a couple of examples.

A spinner consists of a text field on the left side and two buttons with up and down arrows on the right side. If you press the up or down button, the item that displays in the input text will change in a given ordered sequence.

To create a spinner in Swing, you need to use JSpinner class and other model classes. The data of JSpinner is maintained in the instance of SpinnerModel. You can use methods setModel() / getModel() to manipulate the data for the JSpinner. There are some implementations of SpinnerModel which are very useful such as SpinnerNumberModelSpinnerListModel and SpinnerDateModel.

Example of creating spinners with JSpinner and model classes.

In this example, we will create three spinners with different model classes such as SpinnerNumberModel, SpinnerListModel and SpinnerDateModel.

Here is the screenshot of demo application:

JSpinner

Example of handling changed event of JSpinner

In order to handle the changed event of a JSpinner, you just need to add the changed listener to the instance of JSpinner.

In this example, each time current item’s value of the spinner changes, a dialog message will display to show the previous value, current value and next value. Here is the screenshot of the demo application:

JSpinner Demo

  • Was this tutorial helpful ?
  • YesNo