SwingSpinnerTest.java Source code

Java tutorial

Introduction

Here is the source code for SwingSpinnerTest.java

Source

/*
Java Swing, 2nd Edition
By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole
ISBN: 0-596-00408-7
Publisher: O'Reilly 
*/
// SwingSpinnerTest.java
//A quick test of various spinners.
//

import java.awt.Container;
import java.awt.GridLayout;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JSpinner;
import javax.swing.SpinnerDateModel;
import javax.swing.SpinnerListModel;
import javax.swing.SpinnerNumberModel;

public class SwingSpinnerTest extends JFrame {

    public SwingSpinnerTest() {
        super("JSpinner Test");
        setSize(300, 180);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        Container c = getContentPane();
        c.setLayout(new GridLayout(0, 2));

        c.add(new JLabel(" Basic Spinner"));
        c.add(new JSpinner());

        c.add(new JLabel(" Date Spinner"));
        c.add(new JSpinner(new SpinnerDateModel()));

        String weekdays[] = new String[] { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
                "Saturday" };
        c.add(new JLabel(" List Spinner"));
        c.add(new JSpinner(new SpinnerListModel(weekdays)));

        c.add(new JLabel(" Number Spinner"));
        c.add(new JSpinner(new SpinnerNumberModel(0, 0, 100, 5)));

        c.add(new JLabel(" Rollover List Spinner"));
        c.add(new JSpinner(new RolloverSpinnerListModel(weekdays)));

        setVisible(true);
    }

    public static void main(String args[]) {
        new SwingSpinnerTest();
    }
}

class RolloverSpinnerListModel extends SpinnerListModel {

    public RolloverSpinnerListModel(Object[] items) {
        super(items);
    }

    public RolloverSpinnerListModel(List items) {
        super(items);
    }

    public Object getNextValue() {
        Object nv = super.getNextValue();
        if (nv != null) {
            return nv;
        }
        return getList().get(0);
    }

    public Object getPreviousValue() {
        Object pv = super.getPreviousValue();
        if (pv != null) {
            return pv;
        }
        List l = getList();
        return l.get(l.size() - 1);
    }
}