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.
Constructors
// Creates a spinner containing numbers (of SpinnerNumberModel as model) with no minimum/maximum limits JSpinner()
// Creates a spinner with given model where we can set maximum,minimum,step size, type of data JSpinner(SpinnerModel m)
Methods
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()
{
createAndShowGUI();
}
private void createAndShowGUI()
{
setTitle("JSpinner Example");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
s1=new JSpinner();
s2=new JSpinner(m);
//s1.setValue(10);
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();
System.out.println(n.getMinimum());
System.out.println(n.getMaximum());
System.out.println(n.getStepSize());
add(s1);
add(s2);
setSize(400,400);
setVisible(true);
}
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 :)