JSpinner: Selects a value from a range of possible options to Like the drop-down lists, but show no such list. values changed by pressing the scroll buttons. You can also enter a value directly.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerDateModel;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class JavaExampleSpinner extends JFrame implements ChangeListener
{
JLabel LblQty;
JLabel LblDt;
JSpinner Spnr;
JSpinner DateSpnr;
JavaExampleSpinner(String Tytl)
{
setTitle(Tytl);
setSize(500,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container Cntnr=getContentPane();
Cntnr.setLayout(new GridLayout(2,1));
JPanel Pnl=new JPanel();
Pnl.setLayout(new GridLayout(2,2));
Pnl.setBorder(BorderFactory.createTitledBorder("Sale Entry"));
SpinnerNumberModel SpnrNmbrMdl=new SpinnerNumberModel(10,1,100,1);
Spnr=new JSpinner(SpnrNmbrMdl);
Spnr.addChangeListener(this);
Pnl.add(new JLabel("Select Quantity to Be Sold:"));
Pnl.add(Spnr);
Date Dt=new Date();
SpinnerDateModel SpnrDtMdl=new SpinnerDateModel(Dt,null,null,Calendar.DATE);
DateSpnr=new JSpinner(SpnrDtMdl);
DateSpnr.setEditor(new JSpinner.DateEditor(DateSpnr,"dd:MM:yyyy"));
DateSpnr.addChangeListener(this);
Pnl.add(new JLabel("Select Sale Date:"));
Pnl.add(DateSpnr);
Cntnr.add(Pnl,BorderLayout.CENTER);
JPanel Panl=new JPanel();
Panl.setLayout(new FlowLayout());
LblQty=new JLabel();
LblQty.setForeground(Color.GREEN);
LblDt=new JLabel();
LblDt.setForeground(Color.RED);
Panl.add(LblQty);
Panl.add(LblDt);
Panl.setBorder(BorderFactory.createTitledBorder("Information"));
Cntnr.add(Panl);
setVisible(true);
}
public void stateChanged(ChangeEvent ee)
{
JSpinner JSpnr=(JSpinner)ee.getSource();
try
{
JSpnr.commitEdit();
}
catch(ParseException PrsEx){}
if(JSpnr==Spnr)
LblQty.setText("Quantity:"+JSpnr.getValue().toString());
else if(JSpnr==DateSpnr)
LblDt.setText("Date:"+JSpnr.getValue().toString());
}
public static void main(String[] aa)
{
new JavaExampleSpinner("Example Date Spinner In Java");
}
}