Java JSpinner

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Java JSpinner

The object of JSpinner class is a single line input field that allows the user to select a number or an object value from an ordered sequence.

JSpinner class declaration

Let's see the declaration for javax.swing.JSpinner class.

  1. public class JSpinner extends JComponent implements Accessible  

Commonly used Contructors:

Constructor

Description

JSpinner()

It is used to construct a spinner with an Integer SpinnerNumberModel with initial value 0 and no minimum or maximum limits.

JSpinner(SpinnerModel model)

It is used to construct a spinner for a given model.

Commonly used Methods:

Method

Description

void addChangeListener(ChangeListener listener)

It is used to add a listener to the list that is notified each time a change to the model occurs.

Object getValue()

It is used to return the current value of the model.

Java JSpinner Example

  1. import javax.swing.*;    
  2. public class SpinnerExample {  
  3.     public static void main(String[] args) {    
  4.     JFrame f=new JFrame("Spinner Example");    
  5.     SpinnerModel value =  
  6.              new SpinnerNumberModel(5//initial value  
  7.                 0//minimum value  
  8.                 10//maximum value  
  9.                 1); //step  
  10.     JSpinner spinner = new JSpinner(value);   
  11.             spinner.setBounds(100,100,50,30);    
  12.             f.add(spinner);    
  13.             f.setSize(300,300);    
  14.             f.setLayout(null);    
  15.             f.setVisible(true);     
  16. }  
  17. }  

Output:

Java Jspiner 1

Java JSpinner Example with ChangeListener

imp

  1. ort javax.swing.*;    
  2. import javax.swing.event.*;  
  3. public class SpinnerExample {  
  4.     public static void main(String[] args) {    
  5.     JFrame f=new JFrame("Spinner Example");    
  6.     final JLabel label = new JLabel();            
  7.              label.setHorizontalAlignment(JLabel.CENTER);    
  8.              label.setSize(250,100);    
  9.     SpinnerModel value =  
  10.              new SpinnerNumberModel(5//initial value  
  11.                 0//minimum value  
  12.                 10//maximum value  
  13.                 1); //step  
  14.     JSpinner spinner = new JSpinner(value);   
  15.             spinner.setBounds(100,100,50,30);    
  16.             f.add(spinner);  f.add(label);  
  17.            f.setSize(300,300);    
  18.            f.setLayout(null);    
  19.            f.setVisible(true);     
  20.            spinner.addChangeListener(new ChangeListener() {  
  21.         public void stateChanged(ChangeEvent e) {  
  22.          label.setText("Value : " + ((JSpinner)e.getSource()).getValue());  
  23.         }  
  24.      });  
  25. }  
  26. }  

Output:

Java Jspiner 2