2 Ways to Create a JSpinner - Swing

Screenshot of JSpinner Example
Here are 2 ways to create a JSpinner. Before, we do let us talk a bit about the JSpinner. Out of all the swing components, JSpinner is the most easiest one to create. Yes, you heard it right. This component might be a bit unfamiliar however, its advantages are many. Let us look at the two constructors of the class and its methods.


// Creates a spinner containing numbers (of SpinnerNumberModel as model) with no minimum/maximum limits

// Creates a spinner with given model where we can set maximum,minimum,step size, type of data
JSpinner(SpinnerModel m)


public void setValue(int val) // Sets current value to spinner
public int getValue() // Gets the current value

public int getNextValue() // Gets next value
public int getPreviousValue() // Gets previous value

public void setModel(SpinnerModel m) // Sets a model for the JSpinner
public SpinnerModel getModel() // Gets model object of JSpinner

import javax.swing.*;
import java.awt.*;
class JSpinnerExample extends JFrame
JSpinner s1,s2;
// A number model with value of 8, minimum 2, maximum 100 and step size 2
SpinnerNumberModel m=new SpinnerNumberModel(8,2,100,2);

    public JSpinnerExample()
    private void createAndShowGUI()
        setTitle("JSpinner Example");
        setLayout(new FlowLayout());
        s1=new JSpinner();
        s2=new JSpinner(m);
        System.out.println("Value in s1 "+s1.getValue());
        System.out.println("Next value in s1 "+s1.getNextValue());
        System.out.println("Previous value in s1 "+s1.getPreviousValue());
        SpinnerNumberModel n=(SpinnerNumberModel)s1.getModel();
    public static void main(String args[])
        new JSpinnerExample();

The greatest compliment you can give me is when you share this with others. I sincerely appreciate it :)

Posted by at on

Tags: Swing Components,