javacodex.com
Java Examples
Java Examples
memu home questions

JSpinner

A JSpinner component combines the benefits of a JFormattedTextField and an editable JComboBox. It lets you set a list of choices in a JComboBox, and at the same time, you can also apply a format to the displayed value. It shows only one value at a time from the list of choices. It lets you enter a new value.

Source: (JSpinnerExample.java)

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*; 
 
public class JSpinnerExample {
 
  public static void main(String[] arguments) {
 
    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame f = new JFrame("JSpinner Example");
    f.setSize(400,100);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setLayout(new GridLayout(2, 1));
 
    JPanel outputPanel = new JPanel(new FlowLayout());
    JLabel outputLabel = new JLabel("Value: ");
    final JTextField outputText = new JTextField(3);
    outputPanel.add(outputLabel);
    outputPanel.add(outputText);
 
    JPanel spinnerPanel = new JPanel(new FlowLayout());
 
    JLabel spinnerLabel = new JLabel("Spinner:");
    // SpinnerNumberModel(int value, int minimum, int maximum, int stepSize)
    SpinnerModel model = new SpinnerNumberModel(10, 0, 20, 1);
 
    final JSpinner spinner = new JSpinner(model);
    spinnerPanel.add(spinnerLabel);
    spinnerPanel.add(spinner);
 
    spinner.addChangeListener(new ChangeListener() {
      public void stateChanged(ChangeEvent e) {
        outputText.setText("" + spinner.getValue());
      }
    });
 
    f.add(spinnerPanel);
    f.add(outputPanel);
 
    f.setVisible(true);
  }
}
 

Output:

$ java JSpinnerExample

Output



Contact: javacodex@yahoo.com