Swing JSpinner Class



Swing JSpinner Class

package com.c4learn.swing;

import java.awt.FlowLayout;
import java.awt.GridLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerModel;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class JSpinnerDemo {

  private JFrame mainFrame;
  private JLabel headLabel;
  private JLabel msgLabel;
  private JPanel mainPanel;

  public JSpinnerDemo() {
    mainFrame = new JFrame("Java Swing Examples");
    mainFrame.setSize(400, 400);
    mainFrame.setLayout(new GridLayout(3, 1));

    headLabel = new JLabel("Spinner Demo", JLabel.CENTER);
    msgLabel = new JLabel("", JLabel.CENTER);
    mainPanel = new JPanel();
    mainPanel.setLayout(new FlowLayout());

    mainFrame.add(headLabel);
    mainFrame.add(mainPanel);
    mainFrame.add(msgLabel);
    mainFrame.setVisible(true);
  }

  public static void main(String[] args) {
    JSpinnerDemo swingControlDemo = new JSpinnerDemo();
    swingControlDemo.showSpinnerDemo();
  }

  private void showSpinnerDemo() {

    SpinnerModel spinnerModel = new 
                 SpinnerNumberModel(5, 0, 100, 1);
    msgLabel.setText("Spinner Value : 5");
    JSpinner spinner = new JSpinner(spinnerModel);

    spinner.addChangeListener(new ChangeListener() {
      public void stateChanged(ChangeEvent e) {
        msgLabel.setText("Spinner Value : "
            + ((JSpinner) e.getSource()).getValue());
      }
    });

    mainPanel.add(spinner);
    mainFrame.setVisible(true);
  }
}

Output :

Swing Spinner