Recipe 14.10 Choosing a Value with JSpinner


Problem

You want to let the user choose from a fixed set of values, but do not want to use a JList or JComboBox because they take up too much "screen real estate."

Solution

Use a JSpinner.

Discussion

The JSpinner class introduced in JDK 1.4 lets the user click up or down to cycle through a set of values. The values can be of any type, as they are managed by a helper of type SpinnerModel and displayed by another helper of type SpinnerEditor. A series of predefined SpinnerModels handle Numbers, Dates, and Lists (which can be arrays or Collections). A demonstration program is listed in Example 14-6; its output is shown in Figure 14-9.

Example 14-6. SpinnerDemo.java
import java.awt.Container; import java.awt.GridLayout; import javax.swing.*; /**  * Demonstrate the Swing "Spinner" control.  * @author ian  */ public class SpinnerDemo {     public static void main(String[] args) {         JFrame jf = new JFrame("It Spins");         Container cp = jf.getContentPane( );         cp.setLayout(new GridLayout(0,1));         // Create a JSpinner using one of the pre-defined SpinnerModels         JSpinner dates = new JSpinner(new SpinnerDateModel( ));         cp.add(dates);         // Create a JSPinner using a SpinnerListModel.          String[] data = { "One", "Two", "Three" };         JSpinner js = new JSpinner(new SpinnerListModel(data));         cp.add(js);         jf.setSize(100, 80);         jf.setVisible(true);     } }

Figure 14-9. SpinnerDemo output
figs/jcb2_1409.gif


JSpinner's editors are reasonably clever. For example, if you select the leading zero of a number (such as the 04 in 2004), and try to increment it, the editor updates the entire number (04 to 05) rather than producing something silly like 15.

See Also

The earlier Swing classes JList and JComboBox also let you choose among values.



Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net