How do I create a JSpinner component?

Category: javax.swing, viewed: 862 time(s).

JSpinner is a single line input field with two buttons (arrow up and arrow down) that allow us to select a value like number or object from a sequence value. It looks like a combobox without a drop-down.

In the following example we create the default JSpinner that will give us a spinner to select an integer value from it.

package org.kodejava.example.swing;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class JSpinnerCreate extends JFrame {
    public JSpinnerCreate() {
        initialize();
    }

    private void initialize() {
        setSize(300, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        //
        // Create an instance of JSpinner and put it at the top of the frame.
        //
        final JSpinner spinner = new JSpinner();
        getContentPane().add(spinner, BorderLayout.NORTH);

        //
        // Create a JButton and print out the value of the JSpinner when
        // the button is clicked.
        //
        JButton okButton = new JButton("OK");
        okButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Integer value = (Integer) spinner.getValue();
                System.out.println("value = " + value);
            }
        });
        getContentPane().add(okButton, BorderLayout.SOUTH);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new JSpinnerCreate().setVisible(true);
            }
        });
    }
}
Click here to lend your support to: Kode Java Org and make a donation at www.pledgie.com !

 

Can't find what you are looking for? Join our FORUMS and ask some questions!
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Sponsored Links

Our Friends

Statistics

Locations of visitors to this page
visitor stats