How do I create a JSpinner with a SpinnerListModel?

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

This example show you how to create a JSpinner component and pass a SpinnerListModel as the available values of the JSpinner component. The SpinnerListModel can hold a value of collections object and a simple array of object instance.

package org.kodejava.example.swing;

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

public class JSpinnerCreateDemo extends JFrame {
    public JSpinnerCreateDemo() {
        initializeUI();
    }

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

        //
        // Creating an array of color name that we'll use as the
        // source of our SpinnerListMode.
        //
        String[] colors = new String[] {
                "Red", "Orange", "Yellow", "Green", "Blue", "Purple"
        };
        SpinnerListModel model = new SpinnerListModel(colors);

        //
        // Create a JSpinner instance with a spinner model as the value.
        // This JSpinner will allow us to select a colour name when we
        // press the JButton below.
        //
        final JSpinner spinner = new JSpinner(model);
        getContentPane().add(spinner, BorderLayout.NORTH);

        JButton okButton = new JButton("OK");
        okButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String color = (String) spinner.getValue();
                System.out.println("Color = " + color);
            }
        });
        getContentPane().add(okButton, BorderLayout.SOUTH);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new JSpinnerCreateDemo().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