Java如何使用SpinnerListModel创建JSpinner?

本示例说明如何创建JSpinner组件并将aSpinnerListModel作为可用值传递JSpinner。在SpinnerListModel可容纳集合对象的一个值和对象实例的简单阵列。

package org.nhooo.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(WindowConstants.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        // 创建一个颜色名称数组,我们将其用作
        // SpinnerListMode的来源。
        String[] colors = new String[] {
            "Red", "Orange", "Yellow", "Green", "Blue", "Purple"
        };
        SpinnerListModel model = new SpinnerListModel(colors);

        // 创建一个以Spinner模型作为值的JSpinner实例。
        // 当我们使用JSpinner时,我们可以选择颜色名称
        // 按下面的JButton。
        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);
            }
        });
    }
}