NumberSpinner.java
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13: package xeij;
14:
15: import java.lang.*;
16: import java.text.*;
17: import javax.swing.*;
18: import javax.swing.event.*;
19: import javax.swing.text.*;
20:
21: public class NumberSpinner extends JSpinner implements ChangeListener, DocumentListener {
22:
23: protected SpinnerNumberModel model;
24: protected DecimalFormat format;
25: protected JTextField textField;
26:
27:
28:
29:
30:
31: private boolean writeLocked;
32:
33:
34: @SuppressWarnings ("this-escape") public NumberSpinner (SpinnerNumberModel model) {
35: super (model);
36: this.model = model;
37: JSpinner.NumberEditor editor = (JSpinner.NumberEditor) getEditor ();
38: format = editor.getFormat ();
39:
40: textField = editor.getTextField ();
41: writeLocked = false;
42: removeChangeListener (editor);
43: addChangeListener (this);
44: ((AbstractDocument) textField.getDocument ()).addDocumentListener (this);
45: }
46:
47:
48: @Override public void stateChanged (ChangeEvent ce) {
49: if (!writeLocked) {
50: Number modelNumber = model.getNumber ();
51: textField.setText (modelNumber instanceof Double || modelNumber instanceof Float ?
52: format.format (modelNumber.doubleValue ()) :
53: format.format (modelNumber.longValue ()));
54: }
55: }
56:
57:
58: @Override public void changedUpdate (DocumentEvent de) {
59: }
60: @Override public void insertUpdate (DocumentEvent de) {
61: textChanged ();
62: }
63: @Override public void removeUpdate (DocumentEvent de) {
64: textChanged ();
65: }
66: protected void textChanged () {
67: writeLocked = true;
68: Number modelNumber = model.getNumber ();
69: try {
70: Number editorNumber = format.parse (textField.getText ());
71:
72: if (modelNumber instanceof Double || modelNumber instanceof Float) {
73: double modelValue = modelNumber.doubleValue ();
74: double editorValue = editorNumber.doubleValue ();
75: if (modelValue != editorValue &&
76: ((Number) model.getMinimum ()).doubleValue () <= editorValue &&
77: editorValue <= ((Number) model.getMaximum ()).doubleValue ()) {
78: model.setValue (editorNumber);
79: }
80: } else {
81: long modelValue = modelNumber.longValue ();
82: long editorValue = editorNumber.longValue ();
83: if (modelValue != editorValue &&
84: ((Number) model.getMinimum ()).longValue () <= editorValue &&
85: editorValue <= ((Number) model.getMaximum ()).longValue ()) {
86: model.setValue (editorNumber);
87: }
88: }
89: } catch (ParseException pe) {
90: }
91: writeLocked = false;
92: }
93:
94: }
95:
96:
97: