Java Tutorial/Swing/JSpinner — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
(нет различий)
|
Текущая версия на 15:32, 31 мая 2010
Содержание
- 1 A date spinner
- 2 A list spinner
- 3 A spinner of dates
- 4 Creating a JSpinner Component: A number spinner:
- 5 Creating an Hour JSpinner Component
- 6 Creating a SpinnerListModel That Loops Through Its Values
- 7 Creating Custom Spinner Models and Editors
- 8 Creating JSpinner Components
- 9 Customizing a JSpinner Look and Feel
- 10 Customizing the Editor in a JSpinner Component: Create a color spinner
- 11 Custom Models
- 12 Disabling Keyboard Editing in a JSpinner Component
- 13 Implements a custom model and a custom editor for a spinner that displays shades of gray
- 14 Limiting the Values in a Number JSpinner Component
- 15 Listening for Changes to the Value in a JSpinner Component
- 16 Listening for JSpinner Events with a ChangeListener
- 17 Number spinner
- 18 public JSpinner.DateEditor(JSpinner spinner)
- 19 public JSpinner.DateEditor(JSpinner spinner, String dateFormatPattern)
- 20 public JSpinner.NumberEditor(JSpinner spinner)
- 21 public JSpinner.NumberEditor(JSpinner spinner, String decimalFormatPattern)
- 22 public SpinnerDateModel(Date value, Comparable start, Comparable end, int calendarField)
- 23 Setting the Margin Space on a JSpinner Component
- 24 Spinner Date Data
- 25 SpinnerListModel Class: provides for selection from a list of entries, or at least their string representation.
- 26 Spinner Number Model
- 27 SpinnerNumberModel Class: provides for the selection of a number from an open or closed range of values.
- 28 Strings based Spinner
- 29 Use an Icon Editor for use with the JSpinner component
- 30 Using SpinnerDateModel to create JSpinner
A date spinner
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.swing.JSpinner;
import javax.swing.SpinnerDateModel;
public class Main {
public static void main(String[] argv) throws Exception {
SpinnerDateModel dateModel = new SpinnerDateModel();
JSpinner spinner = new JSpinner(dateModel);
Calendar calendar = new GregorianCalendar(2000, Calendar.JANUARY, 1);
spinner.setValue(calendar.getTime());
}
}
A list spinner
import javax.swing.JSpinner;
import javax.swing.SpinnerListModel;
public class Main {
public static void main(String[] argv) throws Exception {
SpinnerListModel listModel = new SpinnerListModel(new String[] { "red","green", "blue" });
JSpinner spinner = new JSpinner(listModel);
spinner.setValue("blue");
}
}
A spinner of dates
import java.awt.FlowLayout;
import java.util.Calendar;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JSpinner;
import javax.swing.SpinnerDateModel;
public class Main extends JFrame {
public Main () {
setSize(200, 100);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout(FlowLayout.LEFT, 4, 4));
add(new JLabel("Expiration Date:"));
Date today = new Date();
JSpinner s = new JSpinner(new SpinnerDateModel(today, null, null, Calendar.MONTH));
JSpinner.DateEditor de = new JSpinner.DateEditor(s, "MM/yy");
s.setEditor(de);
add(s);
setVisible(true);
}
public static void main(String args[]) {
new Main();
}
}
Creating a JSpinner Component: A number spinner:
import javax.swing.JSpinner;
public class Main {
public static void main(String[] argv) throws Exception {
// Create a number spinner
JSpinner spinner = new JSpinner();
// Set its value
spinner.setValue(new Integer(100));
}
}
Creating an Hour JSpinner Component
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.swing.JFormattedTextField;
import javax.swing.JSpinner;
import javax.swing.SpinnerDateModel;
import javax.swing.text.DateFormatter;
import javax.swing.text.DefaultFormatterFactory;
public class Main {
public static void main(String[] argv) throws Exception {
Calendar calendar = new GregorianCalendar();
calendar.set(Calendar.HOUR_OF_DAY, 13); // 1pm
SpinnerDateModel dateModel = new SpinnerDateModel(calendar.getTime(), null,
null, Calendar.HOUR_OF_DAY);
JSpinner spinner = new JSpinner(dateModel);
JFormattedTextField tf = ((JSpinner.DefaultEditor) spinner.getEditor()).getTextField();
DefaultFormatterFactory factory = (DefaultFormatterFactory) tf.getFormatterFactory();
DateFormatter formatter = (DateFormatter) factory.getDefaultFormatter();
// Change the date format to only show the hours
formatter.setFormat(new SimpleDateFormat("hh:00 a"));
//formatter.setFormat(new SimpleDateFormat("HH:00 a"));
}
}
Creating a SpinnerListModel That Loops Through Its Values
import java.util.List;
import javax.swing.JSpinner;
import javax.swing.SpinnerListModel;
public class Main {
public static void main(String[] argv) throws Exception {
SpinnerCircularListModel listModel = new SpinnerCircularListModel(
new String[] { "red", "green", "blue" });
JSpinner spinner = new JSpinner(listModel);
}
}
class SpinnerCircularListModel extends SpinnerListModel {
public SpinnerCircularListModel(Object[] items) {
super(items);
}
public Object getNextValue() {
List list = getList();
int index = list.indexOf(getValue());
index = (index >= list.size() - 1) ? 0 : index + 1;
return list.get(index);
}
public Object getPreviousValue() {
List list = getList();
int index = list.indexOf(getValue());
index = (index <= 0) ? list.size() - 1 : index - 1;
return list.get(index);
}
}
Creating Custom Spinner Models and Editors
/*
*
* Copyright (c) 1998 Sun Microsystems, Inc. All Rights Reserved.
*
* Sun grants you ("Licensee") a non-exclusive, royalty free, license to use,
* modify and redistribute this software in source and binary code form,
* provided that i) this copyright notice and license appear on all copies of
* the software; and ii) Licensee does not utilize the software in a manner
* which is disparaging to Sun.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
* IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE
* LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
* OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS
* LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
* INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
* CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF
* OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*
* This software is not designed or intended for use in on-line control of
* aircraft, air traffic, aircraft navigation or aircraft communications; or in
* the design, construction, operation or maintenance of any nuclear
* facility. Licensee represents and warrants that it will not use or
* redistribute the Software for such purposes.
*/
import javax.swing.JFrame;
import javax.swing.JSpinner;
import javax.swing.SpinnerListModel;
import javax.swing.SpinnerModel;
class CyclingSpinnerListModel extends SpinnerListModel {
Object firstValue, lastValue;
SpinnerModel linkedModel = null;
public CyclingSpinnerListModel(Object[] values) {
super(values);
firstValue = values[0];
lastValue = values[values.length - 1];
}
public void setLinkedModel(SpinnerModel linkedModel) {
this.linkedModel = linkedModel;
}
public Object getNextValue() {
Object value = super.getNextValue();
if (value == null) {
value = firstValue;
if (linkedModel != null) {
linkedModel.setValue(linkedModel.getNextValue());
}
}
return value;
}
public Object getPreviousValue() {
Object value = super.getPreviousValue();
if (value == null) {
value = lastValue;
if (linkedModel != null) {
linkedModel.setValue(linkedModel.getPreviousValue());
}
}
return value;
}
}
public class CyclingSpinnerListModelDemo {
public static void main(String[] a) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JSpinner spinner = new JSpinner(new CyclingSpinnerListModel(new String[]{"A","B","C"}));
frame.add(spinner);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
Creating JSpinner Components
The JSpinner class includes two constructors for initializing the component:
public JSpinner()
JSpinner spinner = new JSpinner();
public JSpinner(SpinnerModel model)
SpinnerModel model = new SpinnerListModel(args);
JSpinner spinner = new JSpinner(model);
Customizing a JSpinner Look and Feel
Property StringObject TypeSpinner.actionMapActionMapSpinner.ancestorInputMapInputMapSpinner.arrowButtonBorderBorderSpinner.arrowButtonInsetsInsetsSpinner.arrowButtonSizeDimensionSpinner.backgroundColorSpinner.borderBorderSpinner.editorBorderPaintedBooleanSpinner.fontFontSpinner.foregroundColorSpinnerUIString
Customizing the Editor in a JSpinner Component: Create a color spinner
import java.awt.Color;
import java.awt.Dimension;
import java.lang.reflect.Field;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerListModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class Main {
public static void main(String[] argv) throws Exception {
ColorSpinner spinner = new ColorSpinner(new String[] { "red", "green","blue" });
spinner.setValue("blue");
}
}
class ColorSpinner extends JSpinner {
public ColorSpinner(String[] colorNames) {
super();
setModel(new SpinnerListModel(colorNames));
setEditor(new Editor(this));
}
public class Editor extends JPanel implements ChangeListener {
int preferredWidth = 30;
int preferredHeight = 16;
Editor(JSpinner spinner) {
spinner.addChangeListener(this);
setPreferredSize(new Dimension(preferredWidth, preferredHeight));
setColor((String) spinner.getValue());
}
public void stateChanged(ChangeEvent evt) {
JSpinner spinner = (JSpinner) evt.getSource();
String value = (String) spinner.getValue();
setColor(value);
}
public void setColor(String colorName) {
try {
Field field = Class.forName("java.awt.Color").getField(colorName);
Color color = (Color) field.get(null);
setBackground(color);
} catch (Exception e) {
}
}
}
}
Custom Models
import java.awt.BorderLayout;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerListModel;
class RolloverSpinnerListModel extends SpinnerListModel {
public RolloverSpinnerListModel(List<?> values) {
super(values);
}
public RolloverSpinnerListModel(Object[] values) {
super(values);
}
public Object getNextValue() {
Object returnValue = super.getNextValue();
if (returnValue == null) {
returnValue = getList().get(0);
}
return returnValue;
}
public Object getPreviousValue() {
Object returnValue = super.getPreviousValue();
if (returnValue == null) {
List list = getList();
returnValue = list.get(list.size() - 1);
}
return returnValue;
}
}
public class RolloverSpinnerListModelSample {
public static void main(String args[]) {
JFrame frame = new JFrame("JSpinner Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String[] values = new String[]{"a","b","c"};
RolloverSpinnerListModel model = new RolloverSpinnerListModel(values);
JSpinner spinner1 = new JSpinner(model);
JPanel panel1 = new JPanel(new BorderLayout());
panel1.add(spinner1, BorderLayout.CENTER);
frame.add(panel1, BorderLayout.SOUTH);
frame.setSize(200, 90);
frame.setVisible(true);
}
}
Disabling Keyboard Editing in a JSpinner Component
import java.awt.Color;
import javax.swing.JFormattedTextField;
import javax.swing.JSpinner;
public class Main {
public static void main(String[] argv) throws Exception {
JSpinner spinner = new JSpinner();
// Disable keyboard edits in the spinner
JFormattedTextField tf = ((JSpinner.DefaultEditor) spinner.getEditor()).getTextField();
tf.setEditable(false);
tf.setBackground(Color.white);
// The value of the spinner can still be programmatically changed
spinner.setValue(new Integer(100));
}
}
Implements a custom model and a custom editor for a spinner that displays shades of gray
/*
*
* Copyright (c) 1998 Sun Microsystems, Inc. All Rights Reserved.
*
* Sun grants you ("Licensee") a non-exclusive, royalty free, license to use,
* modify and redistribute this software in source and binary code form,
* provided that i) this copyright notice and license appear on all copies of
* the software; and ii) Licensee does not utilize the software in a manner
* which is disparaging to Sun.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
* IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE
* LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
* OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS
* LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
* INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
* CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF
* OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*
* This software is not designed or intended for use in on-line control of
* aircraft, air traffic, aircraft navigation or aircraft communications; or in
* the design, construction, operation or maintenance of any nuclear
* facility. Licensee represents and warrants that it will not use or
* redistribute the Software for such purposes.
*/
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
class GrayModel extends SpinnerNumberModel {
public GrayModel(int value) {
super(value, 0, 255, 5);
}
public int getIntValue() {
Integer myValue = (Integer) getValue();
return myValue.intValue();
}
public Color getColor() {
int intValue = getIntValue();
return new Color(intValue, intValue, intValue);
}
}
class GrayEditor extends JLabel implements ChangeListener {
public GrayEditor(JSpinner spinner) {
setOpaque(true);
// Get info from the model.
GrayModel myModel = (GrayModel) (spinner.getModel());
setBackground(myModel.getColor());
spinner.addChangeListener(this);
// Set tool tip text.
updateToolTipText(spinner);
// Set size info.
Dimension size = new Dimension(60, 15);
setMinimumSize(size);
setPreferredSize(size);
}
protected void updateToolTipText(JSpinner spinner) {
String toolTipText = spinner.getToolTipText();
if (toolTipText != null) {
// JSpinner has tool tip text. Use it.
if (!toolTipText.equals(getToolTipText())) {
setToolTipText(toolTipText);
}
} else {
// Define our own tool tip text.
GrayModel myModel = (GrayModel) (spinner.getModel());
int rgb = myModel.getIntValue();
setToolTipText("(" + rgb + "," + rgb + "," + rgb + ")");
}
}
public void stateChanged(ChangeEvent e) {
JSpinner mySpinner = (JSpinner) (e.getSource());
GrayModel myModel = (GrayModel) (mySpinner.getModel());
setBackground(myModel.getColor());
updateToolTipText(mySpinner);
}
}
public class SpinnerDemo4 extends JPanel {
public static void main(String[] args) {
JFrame frame = new JFrame("SpinnerDemo4");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent newContentPane = new SpinnerDemo4();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.add(new JLabel("Shade of Gray:"), "North");
frame.add(new JSpinner(new GrayModel(170)));
frame.pack();
frame.setVisible(true);
}
}
Limiting the Values in a Number JSpinner Component
import javax.swing.JSpinner;
import javax.swing.SpinnerModel;
import javax.swing.SpinnerNumberModel;
public class Main {
public static void main(String[] argv) throws Exception {
// Create a number spinner that only handles values in the range [0,100]
int min = 0;
int max = 100;
int step = 5;
int initValue = 50;
SpinnerModel model = new SpinnerNumberModel(initValue, min, max, step);
JSpinner spinner = new JSpinner(model);
}
}
Listening for Changes to the Value in a JSpinner Component
import javax.swing.JSpinner;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class Main {
public static void main(String[] argv) throws Exception {
JSpinner spinner = new JSpinner();
spinner.addChangeListener(new SpinnerListener());
spinner.setValue(new Integer(100));
}
}
class SpinnerListener implements ChangeListener {
public void stateChanged(ChangeEvent evt) {
JSpinner spinner = (JSpinner) evt.getSource();
// Get the new value
Object value = spinner.getValue();
}
}
Listening for JSpinner Events with a ChangeListener
import java.awt.BorderLayout;
import java.text.DateFormatSymbols;
import java.util.Locale;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerListModel;
import javax.swing.SpinnerModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class SpinnerChangeListenerSample {
public static void main(String args[]) {
JFrame frame = new JFrame("JSpinner Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DateFormatSymbols symbols = new DateFormatSymbols(Locale.FRENCH);
String days[] = symbols.getWeekdays();
SpinnerModel model1 = new SpinnerListModel(days);
JSpinner spinner1 = new JSpinner(model1);
ChangeListener listener = new ChangeListener() {
public void stateChanged(ChangeEvent e) {
System.out.println("Source: " + e.getSource());
}
};
spinner1.addChangeListener(listener);
JLabel label1 = new JLabel("French Days/List");
JPanel panel1 = new JPanel(new BorderLayout());
panel1.add(label1, BorderLayout.WEST);
panel1.add(spinner1, BorderLayout.CENTER);
frame.add(panel1, BorderLayout.NORTH);
frame.setSize(200, 90);
frame.setVisible(true);
}
}
Number spinner
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JSpinner;
import javax.swing.SpinnerDateModel;
import javax.swing.SpinnerListModel;
import javax.swing.SpinnerNumberModel;
public class Main extends JFrame {
public Main() {
JSpinner m_numberSpinner;
SpinnerNumberModel m_numberSpinnerModel;
Double current = new Double(5.50);
Double min = new Double(0.00);
Double max = new Double(10.00);
Double step = new Double(0.25);
m_numberSpinnerModel = new SpinnerNumberModel(current, min, max, step);
m_numberSpinner = new JSpinner(m_numberSpinnerModel);
add(m_numberSpinner);
}
public static void main(String argv[]) {
Main spinnerFrame = new Main();
spinnerFrame.setSize(350, 200);
spinnerFrame.setVisible(true);
}
}
public JSpinner.DateEditor(JSpinner spinner)
The DateEditor allows you to customize the date display (and entry) using various aspects of the SimpleDateFormat class of the java.text package.
import java.awt.BorderLayout;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerDateModel;
import javax.swing.SpinnerModel;
public class SpinnerDateEditorSample1 {
public static void main(String args[]) {
JFrame frame = new JFrame("JSpinner Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SpinnerModel model = new SpinnerDateModel();
JSpinner spinner = new JSpinner(model);
JComponent editor = new JSpinner.DateEditor(spinner);
spinner.setEditor(editor);
JPanel panel1 = new JPanel(new BorderLayout());
panel1.add(spinner, BorderLayout.CENTER);
frame.add(panel1, BorderLayout.SOUTH);
frame.setSize(200, 90);
frame.setVisible(true);
}
}
public JSpinner.DateEditor(JSpinner spinner, String dateFormatPattern)
import java.awt.BorderLayout;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerDateModel;
import javax.swing.SpinnerModel;
public class SpinnerDateEditorSample {
public static void main(String args[]) {
JFrame frame = new JFrame("JSpinner Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SpinnerModel model = new SpinnerDateModel();
JSpinner spinner = new JSpinner(model);
JComponent editor = new JSpinner.DateEditor(spinner, "MMMM yyyy");
spinner.setEditor(editor);
JPanel panel1 = new JPanel(new BorderLayout());
panel1.add(spinner, BorderLayout.CENTER);
frame.add(panel1, BorderLayout.SOUTH);
frame.setSize(200, 90);
frame.setVisible(true);
}
}
public JSpinner.NumberEditor(JSpinner spinner)
import java.awt.BorderLayout;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerModel;
import javax.swing.SpinnerNumberModel;
public class SpinnerNumberEditorSample1 {
public static void main(String args[]) {
JFrame frame = new JFrame("JSpinner Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SpinnerModel model = new SpinnerNumberModel(50, 0, 100, .25);
JSpinner spinner = new JSpinner(model);
JComponent editor = new JSpinner.NumberEditor(spinner);
spinner.setEditor(editor);
JPanel panel1 = new JPanel(new BorderLayout());
panel1.add(spinner, BorderLayout.CENTER);
frame.add(panel1, BorderLayout.SOUTH);
frame.setSize(200, 90);
frame.setVisible(true);
}
}
public JSpinner.NumberEditor(JSpinner spinner, String decimalFormatPattern)
import java.awt.BorderLayout;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerModel;
import javax.swing.SpinnerNumberModel;
public class SpinnerNumberEditorSample2 {
public static void main(String args[]) {
JFrame frame = new JFrame("JSpinner Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SpinnerModel model = new SpinnerNumberModel(50, 0, 100, .25);
JSpinner spinner = new JSpinner(model);
JComponent editor = new JSpinner.NumberEditor(spinner, "#,##0.###");
spinner.setEditor(editor);
JPanel panel1 = new JPanel(new BorderLayout());
panel1.add(spinner, BorderLayout.CENTER);
frame.add(panel1, BorderLayout.SOUTH);
frame.setSize(200, 90);
frame.setVisible(true);
}
}
public SpinnerDateModel(Date value, Comparable start, Comparable end, int calendarField)
import java.awt.BorderLayout;
import java.util.Calendar;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerDateModel;
import javax.swing.SpinnerModel;
public class SpinnerDateStartEndSample {
public static void main(String args[]) {
JFrame frame = new JFrame("JSpinner Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Calendar cal = Calendar.getInstance();
Date now = cal.getTime();
cal.add(Calendar.YEAR, -50);
Date startDate = cal.getTime();
cal.add(Calendar.YEAR, 100);
Date endDate = cal.getTime();
SpinnerModel model = new SpinnerDateModel(now, startDate, endDate, Calendar.YEAR);
JSpinner spinner1 = new JSpinner(model);
JPanel panel1 = new JPanel(new BorderLayout());
panel1.add(spinner1, BorderLayout.CENTER);
frame.add(panel1, BorderLayout.SOUTH);
frame.setSize(200, 90);
frame.setVisible(true);
}
}
Setting the Margin Space on a JSpinner Component
import java.awt.Insets;
import javax.swing.JFormattedTextField;
import javax.swing.JSpinner;
public class Main {
public static void main(String[] argv) throws Exception {
JSpinner spinner = new JSpinner();
// Get the text field
JFormattedTextField tf = ((JSpinner.DefaultEditor) spinner.getEditor()).getTextField();
// Set the margin (add two spaces to the left and right side of the value)
int top = 0;
int left = 2;
int bottom = 0;
int right = 2;
Insets insets = new Insets(top, left, bottom, right);
tf.setMargin(insets);
}
}
Spinner Date Data
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerDateModel;
import javax.swing.SpinnerModel;
public class SpinnerDateSample {
public static void main(String args[]) {
JFrame frame = new JFrame("JSpinner Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SpinnerModel model1 = new SpinnerDateModel();
JSpinner spinner1 = new JSpinner(model1);
JLabel label1 = new JLabel("Dates/Date");
JPanel panel1 = new JPanel(new BorderLayout());
panel1.add(label1, BorderLayout.WEST);
panel1.add(spinner1, BorderLayout.CENTER);
frame.add(panel1, BorderLayout.CENTER);
frame.setSize(200, 90);
frame.setVisible(true);
}
}
SpinnerListModel Class: provides for selection from a list of entries, or at least their string representation.
public SpinnerListModel()
SpinnerModel model = new SpinnerListModel();
JSpinner spinner = new JSpinner(model);
public SpinnerListModel(List<?> values)
List<String> list = args;
SpinnerModel model = new SpinnerListModel(list);
JSpinner spinner = new JSpinner(model);
public SpinnerListModel(Object[] values)
SpinnerModel model = new SpinnerListModel(args);
JSpinner spinner = new JSpinner(model);
Spinner Number Model
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerModel;
import javax.swing.SpinnerNumberModel;
public class SpinnerNumberSample {
public static void main(String args[]) {
JFrame frame = new JFrame("JSpinner Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SpinnerModel model1 = new SpinnerNumberModel();
JSpinner spinner1 = new JSpinner(model1);
JLabel label1 = new JLabel("Numbers");
JPanel panel1 = new JPanel(new BorderLayout());
panel1.add(label1, BorderLayout.WEST);
panel1.add(spinner1, BorderLayout.CENTER);
frame.add(panel1, BorderLayout.SOUTH);
frame.setSize(200, 90);
frame.setVisible(true);
}
}
SpinnerNumberModel Class: provides for the selection of a number from an open or closed range of values.
That number can be any of the subclasses of Number, including Integer and Double.
public SpinnerNumberModel()
SpinnerModel model = new SpinnerNumberModel();
JSpinner spinner = new JSpinner(model);
public SpinnerNumberModel(double value, double minimum, double maximum, double stepSize)
SpinnerModel model = new SpinnerNumberModel(50, 0, 100, .25);
JSpinner spinner = new JSpinner(model);
public SpinnerNumberModel(int value, int minimum, int maximum, int stepSize)
SpinnerModel model = new SpinnerNumberModel(50, 0, 100, 1);
JSpinner spinner = new JSpinner(model);
public SpinnerNumberModel(Number value, Comparable minimum, Comparable maximum, Number stepSize)
Number value = new Integer(50);
Number min = new Integer(0);
Number max = new Integer(100);
Number step = new Integer(1);
SpinnerModel model = new SpinnerNumberModel(value, min, max, step);
JSpinner spinner = new JSpinner(model);
Strings based Spinner
import java.awt.BorderLayout;
import java.text.DateFormatSymbols;
import java.util.Locale;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerListModel;
import javax.swing.SpinnerModel;
public class SpinnerStringsSample {
public static void main(String args[]) {
JFrame frame = new JFrame("JSpinner Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DateFormatSymbols symbols = new DateFormatSymbols(Locale.FRENCH);
String days[] = symbols.getWeekdays();
SpinnerModel model1 = new SpinnerListModel(days);
JSpinner spinner1 = new JSpinner(model1);
JLabel label1 = new JLabel("French Days/List");
JPanel panel1 = new JPanel(new BorderLayout());
panel1.add(label1, BorderLayout.WEST);
panel1.add(spinner1, BorderLayout.CENTER);
frame.add(panel1, BorderLayout.NORTH);
frame.setSize(200, 90);
frame.setVisible(true);
}
}
Use an Icon Editor for use with the JSpinner component
import javax.swing.Icon;
import javax.swing.JLabel;
import javax.swing.JSpinner;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
class IconEditor extends JLabel implements ChangeListener {
JSpinner spinner;
Icon icon;
public IconEditor(JSpinner s) {
super((Icon)s.getValue(), CENTER);
icon = (Icon)s.getValue();
spinner = s;
spinner.addChangeListener(this);
}
public void stateChanged(ChangeEvent ce) {
icon = (Icon)spinner.getValue();
setIcon(icon);
}
public JSpinner getSpinner() { return spinner; }
public Icon getIcon() { return icon; }
}
Using SpinnerDateModel to create JSpinner
public SpinnerDateModel()
SpinnerModel model = new SpinnerDateModel();
JSpinner spinner = new JSpinner(model);
Calendar cal = Calendar.getInstance();
Date now = cal.getTime();
cal.add(Calendar.YEAR, -50);
Date startDate = cal.getTime();
cal.add(Calendar.YEAR, 100);
Date endDate = cal.getTime();
SpinnerModel model = new SpinnerDateModel(now, startDate, endDate, Calendar.YEAR);
JSpinner spinner = new JSpinner(model);