- Notifications
You must be signed in to change notification settings - Fork 5.8k
/
Copy pathJSpinner.java
2107 lines (1907 loc) · 75.9 KB
/
JSpinner.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2000, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
packagejavax.swing;
importjava.awt.Component;
importjava.awt.ComponentOrientation;
importjava.awt.Container;
importjava.awt.Dimension;
importjava.awt.Font;
importjava.awt.Insets;
importjava.awt.LayoutManager;
importjava.awt.Point;
importjava.awt.Rectangle;
importjava.awt.event.ActionEvent;
importjava.beans.BeanProperty;
importjava.beans.JavaBean;
importjava.beans.PropertyChangeEvent;
importjava.beans.PropertyChangeListener;
importjava.io.IOException;
importjava.io.ObjectOutputStream;
importjava.io.Serial;
importjava.io.Serializable;
importjava.text.DateFormat;
importjava.text.DecimalFormat;
importjava.text.NumberFormat;
importjava.text.ParseException;
importjava.text.SimpleDateFormat;
importjava.text.spi.DateFormatProvider;
importjava.text.spi.NumberFormatProvider;
importjava.util.Date;
importjava.util.Locale;
importjavax.accessibility.Accessible;
importjavax.accessibility.AccessibleAction;
importjavax.accessibility.AccessibleContext;
importjavax.accessibility.AccessibleEditableText;
importjavax.accessibility.AccessibleRole;
importjavax.accessibility.AccessibleText;
importjavax.accessibility.AccessibleValue;
importjavax.swing.event.ChangeEvent;
importjavax.swing.event.ChangeListener;
importjavax.swing.event.EventListenerList;
importjavax.swing.plaf.FontUIResource;
importjavax.swing.plaf.SpinnerUI;
importjavax.swing.plaf.UIResource;
importjavax.swing.text.AttributeSet;
importjavax.swing.text.BadLocationException;
importjavax.swing.text.DateFormatter;
importjavax.swing.text.DefaultFormatterFactory;
importjavax.swing.text.DocumentFilter;
importjavax.swing.text.NumberFormatter;
importsun.util.locale.provider.LocaleProviderAdapter;
importsun.util.locale.provider.LocaleResources;
/**
* A single line input field that lets the user select a
* number or an object value from an ordered sequence. Spinners typically
* provide a pair of tiny arrow buttons for stepping through the elements
* of the sequence. The keyboard up/down arrow keys also cycle through the
* elements. The user may also be allowed to type a (legal) value directly
* into the spinner. Although combo boxes provide similar functionality,
* spinners are sometimes preferred because they don't require a drop down list
* that can obscure important data.
* <p>
* A <code>JSpinner</code>'s sequence value is defined by its
* <code>SpinnerModel</code>.
* The <code>model</code> can be specified as a constructor argument and
* changed with the <code>model</code> property. <code>SpinnerModel</code>
* classes for some common types are provided: <code>SpinnerListModel</code>,
* <code>SpinnerNumberModel</code>, and <code>SpinnerDateModel</code>.
* <p>
* A <code>JSpinner</code> has a single child component that's
* responsible for displaying
* and potentially changing the current element or <i>value</i> of
* the model, which is called the <code>editor</code>. The editor is created
* by the <code>JSpinner</code>'s constructor and can be changed with the
* <code>editor</code> property. The <code>JSpinner</code>'s editor stays
* in sync with the model by listening for <code>ChangeEvent</code>s. If the
* user has changed the value displayed by the <code>editor</code> it is
* possible for the <code>model</code>'s value to differ from that of
* the <code>editor</code>. To make sure the <code>model</code> has the same
* value as the editor use the <code>commitEdit</code> method, eg:
* <pre>
* try {
* spinner.commitEdit();
* }
* catch (ParseException pe) {
* // Edited value is invalid, spinner.getValue() will return
* // the last valid value, you could revert the spinner to show that:
* JComponent editor = spinner.getEditor();
* if (editor instanceof DefaultEditor) {
* ((DefaultEditor)editor).getTextField().setValue(spinner.getValue());
* }
* // reset the value to some known value:
* spinner.setValue(fallbackValue);
* // or treat the last valid value as the current, in which
* // case you don't need to do anything.
* }
* return spinner.getValue();
* </pre>
* <p>
* For information and examples of using spinner see
* <a href="https://docs.oracle.com/javase/tutorial/uiswing/components/spinner.html">How to Use Spinners</a>,
* a section in <em>The Java Tutorial.</em>
* <p>
* <strong>Warning:</strong> Swing is not thread safe. For more
* information see <a
* href="package-summary.html#threading">Swing's Threading
* Policy</a>.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @see SpinnerModel
* @see AbstractSpinnerModel
* @see SpinnerListModel
* @see SpinnerNumberModel
* @see SpinnerDateModel
* @see JFormattedTextField
*
* @author Hans Muller
* @author Lynn Monsanto (accessibility)
* @since 1.4
*/
@JavaBean(defaultProperty = "UI", description = "A single line input field that lets the user select a number or an object value from an ordered set.")
@SwingContainer(false)
@SuppressWarnings("serial") // Same-version serialization only
publicclassJSpinnerextendsJComponentimplementsAccessible
{
/**
* @see #getUIClassID
* @see #readObject
*/
privatestaticfinalStringuiClassID = "SpinnerUI";
privatestaticfinalActionDISABLED_ACTION = newDisabledAction();
privateSpinnerModelmodel;
privateJComponenteditor;
privateChangeListenermodelListener;
privatetransientChangeEventchangeEvent;
privatebooleaneditorExplicitlySet = false;
/**
* Constructs a spinner for the given model. The spinner has
* a set of previous/next buttons, and an editor appropriate
* for the model.
*
* @param model a model for the new spinner
* @throws NullPointerException if the model is {@code null}
*/
publicJSpinner(SpinnerModelmodel) {
if (model == null) {
thrownewNullPointerException("model cannot be null");
}
this.model = model;
this.editor = createEditor(model);
setUIProperty("opaque",true);
updateUI();
}
/**
* Constructs a spinner with an <code>Integer SpinnerNumberModel</code>
* with initial value 0 and no minimum or maximum limits.
*/
publicJSpinner() {
this(newSpinnerNumberModel());
}
/**
* Returns the look and feel (L&F) object that renders this component.
*
* @return the <code>SpinnerUI</code> object that renders this component
*/
publicSpinnerUIgetUI() {
return (SpinnerUI)ui;
}
/**
* Sets the look and feel (L&F) object that renders this component.
*
* @param ui the <code>SpinnerUI</code> L&F object
* @see UIDefaults#getUI
*/
publicvoidsetUI(SpinnerUIui) {
super.setUI(ui);
}
/**
* Returns the suffix used to construct the name of the look and feel
* (L&F) class used to render this component.
*
* @return the string "SpinnerUI"
* @see JComponent#getUIClassID
* @see UIDefaults#getUI
*/
@BeanProperty(bound = false)
publicStringgetUIClassID() {
returnuiClassID;
}
/**
* Resets the UI property with the value from the current look and feel.
*
* @see UIManager#getUI
*/
publicvoidupdateUI() {
setUI((SpinnerUI)UIManager.getUI(this));
invalidate();
}
/**
* This method is called by the constructors to create the
* <code>JComponent</code>
* that displays the current value of the sequence. The editor may
* also allow the user to enter an element of the sequence directly.
* An editor must listen for <code>ChangeEvents</code> on the
* <code>model</code> and keep the value it displays
* in sync with the value of the model.
* <p>
* Subclasses may override this method to add support for new
* <code>SpinnerModel</code> classes. Alternatively one can just
* replace the editor created here with the <code>setEditor</code>
* method. The default mapping from model type to editor is:
* <ul>
* <li> <code>SpinnerNumberModel => JSpinner.NumberEditor</code>
* <li> <code>SpinnerDateModel => JSpinner.DateEditor</code>
* <li> <code>SpinnerListModel => JSpinner.ListEditor</code>
* <li> <i>all others</i> => <code>JSpinner.DefaultEditor</code>
* </ul>
*
* @return a component that displays the current value of the sequence
* @param model the value of getModel
* @see #getModel
* @see #setEditor
*/
protectedJComponentcreateEditor(SpinnerModelmodel) {
if (modelinstanceofSpinnerDateModel) {
returnnewDateEditor(this);
}
elseif (modelinstanceofSpinnerListModel) {
returnnewListEditor(this);
}
elseif (modelinstanceofSpinnerNumberModel) {
returnnewNumberEditor(this);
}
else {
returnnewDefaultEditor(this);
}
}
/**
* Changes the model that represents the value of this spinner.
* If the editor property has not been explicitly set,
* the editor property is (implicitly) set after the <code>"model"</code>
* <code>PropertyChangeEvent</code> has been fired. The editor
* property is set to the value returned by <code>createEditor</code>,
* as in:
* <pre>
* setEditor(createEditor(model));
* </pre>
*
* @param model the new <code>SpinnerModel</code>
* @see #getModel
* @see #getEditor
* @see #setEditor
* @throws IllegalArgumentException if model is <code>null</code>
*/
@BeanProperty(visualUpdate = true, description
= "Model that represents the value of this spinner.")
publicvoidsetModel(SpinnerModelmodel) {
if (model == null) {
thrownewIllegalArgumentException("null model");
}
if (!model.equals(this.model)) {
SpinnerModeloldModel = this.model;
this.model = model;
if (modelListener != null) {
oldModel.removeChangeListener(modelListener);
this.model.addChangeListener(modelListener);
}
firePropertyChange("model", oldModel, model);
if (!editorExplicitlySet) {
setEditor(createEditor(model)); // sets editorExplicitlySet true
editorExplicitlySet = false;
}
repaint();
revalidate();
}
}
/**
* Returns the <code>SpinnerModel</code> that defines
* this spinners sequence of values.
*
* @return the value of the model property
* @see #setModel
*/
publicSpinnerModelgetModel() {
returnmodel;
}
/**
* Returns the current value of the model, typically
* this value is displayed by the <code>editor</code>. If the
* user has changed the value displayed by the <code>editor</code> it is
* possible for the <code>model</code>'s value to differ from that of
* the <code>editor</code>, refer to the class level javadoc for examples
* of how to deal with this.
* <p>
* This method simply delegates to the <code>model</code>.
* It is equivalent to:
* <pre>
* getModel().getValue()
* </pre>
*
* @return the current value of the model
* @see #setValue
* @see SpinnerModel#getValue
*/
publicObjectgetValue() {
returngetModel().getValue();
}
/**
* Changes current value of the model, typically
* this value is displayed by the <code>editor</code>.
* If the <code>SpinnerModel</code> implementation
* doesn't support the specified value then an
* <code>IllegalArgumentException</code> is thrown.
* <p>
* This method simply delegates to the <code>model</code>.
* It is equivalent to:
* <pre>
* getModel().setValue(value)
* </pre>
*
* @param value new value for the spinner
* @throws IllegalArgumentException if <code>value</code> isn't allowed
* @see #getValue
* @see SpinnerModel#setValue
*/
publicvoidsetValue(Objectvalue) {
getModel().setValue(value);
}
/**
* Returns the object in the sequence that comes after the object returned
* by <code>getValue()</code>. If the end of the sequence has been reached
* then return <code>null</code>.
* Calling this method does not effect <code>value</code>.
* <p>
* This method simply delegates to the <code>model</code>.
* It is equivalent to:
* <pre>
* getModel().getNextValue()
* </pre>
*
* @return the next legal value or <code>null</code> if one doesn't exist
* @see #getValue
* @see #getPreviousValue
* @see SpinnerModel#getNextValue
*/
@BeanProperty(bound = false)
publicObjectgetNextValue() {
returngetModel().getNextValue();
}
/**
* We pass <code>Change</code> events along to the listeners with the
* the slider (instead of the model itself) as the event source.
*/
privateclassModelListenerimplementsChangeListener, Serializable {
publicvoidstateChanged(ChangeEvente) {
fireStateChanged();
}
}
/**
* Adds a listener to the list that is notified each time a change
* to the model occurs. The source of <code>ChangeEvents</code>
* delivered to <code>ChangeListeners</code> will be this
* <code>JSpinner</code>. Note also that replacing the model
* will not affect listeners added directly to JSpinner.
* Applications can add listeners to the model directly. In that
* case is that the source of the event would be the
* <code>SpinnerModel</code>.
*
* @param listener the <code>ChangeListener</code> to add
* @see #removeChangeListener
* @see #getModel
*/
publicvoidaddChangeListener(ChangeListenerlistener) {
if (modelListener == null) {
modelListener = newModelListener();
getModel().addChangeListener(modelListener);
}
listenerList.add(ChangeListener.class, listener);
}
/**
* Removes a <code>ChangeListener</code> from this spinner.
*
* @param listener the <code>ChangeListener</code> to remove
* @see #fireStateChanged
* @see #addChangeListener
*/
publicvoidremoveChangeListener(ChangeListenerlistener) {
listenerList.remove(ChangeListener.class, listener);
}
/**
* Returns an array of all the <code>ChangeListener</code>s added
* to this JSpinner with addChangeListener().
*
* @return all of the <code>ChangeListener</code>s added or an empty
* array if no listeners have been added
* @since 1.4
*/
@BeanProperty(bound = false)
publicChangeListener[] getChangeListeners() {
returnlistenerList.getListeners(ChangeListener.class);
}
/**
* Sends a <code>ChangeEvent</code>, whose source is this
* <code>JSpinner</code>, to each <code>ChangeListener</code>.
* When a <code>ChangeListener</code> has been added
* to the spinner, this method is called each time
* a <code>ChangeEvent</code> is received from the model.
*
* @see #addChangeListener
* @see #removeChangeListener
* @see EventListenerList
*/
protectedvoidfireStateChanged() {
Object[] listeners = listenerList.getListenerList();
for (inti = listeners.length - 2; i >= 0; i -= 2) {
if (listeners[i] == ChangeListener.class) {
if (changeEvent == null) {
changeEvent = newChangeEvent(this);
}
((ChangeListener)listeners[i+1]).stateChanged(changeEvent);
}
}
}
/**
* Returns the object in the sequence that comes
* before the object returned by <code>getValue()</code>.
* If the end of the sequence has been reached then
* return <code>null</code>. Calling this method does
* not effect <code>value</code>.
* <p>
* This method simply delegates to the <code>model</code>.
* It is equivalent to:
* <pre>
* getModel().getPreviousValue()
* </pre>
*
* @return the previous legal value or <code>null</code>
* if one doesn't exist
* @see #getValue
* @see #getNextValue
* @see SpinnerModel#getPreviousValue
*/
@BeanProperty(bound = false)
publicObjectgetPreviousValue() {
returngetModel().getPreviousValue();
}
/**
* Changes the <code>JComponent</code> that displays the current value
* of the <code>SpinnerModel</code>. It is the responsibility of this
* method to <i>disconnect</i> the old editor from the model and to
* connect the new editor. This may mean removing the
* old editors <code>ChangeListener</code> from the model or the
* spinner itself and adding one for the new editor.
*
* @param editor the new editor
* @see #getEditor
* @see #createEditor
* @see #getModel
* @throws IllegalArgumentException if editor is <code>null</code>
*/
@BeanProperty(visualUpdate = true, description
= "JComponent that displays the current value of the model")
publicvoidsetEditor(JComponenteditor) {
if (editor == null) {
thrownewIllegalArgumentException("null editor");
}
if (!editor.equals(this.editor)) {
JComponentoldEditor = this.editor;
this.editor = editor;
if (oldEditorinstanceofDefaultEditor) {
((DefaultEditor)oldEditor).dismiss(this);
}
editorExplicitlySet = true;
firePropertyChange("editor", oldEditor, editor);
revalidate();
repaint();
}
}
/**
* Returns the component that displays and potentially
* changes the model's value.
*
* @return the component that displays and potentially
* changes the model's value
* @see #setEditor
* @see #createEditor
*/
publicJComponentgetEditor() {
returneditor;
}
/**
* Commits the currently edited value to the <code>SpinnerModel</code>.
* <p>
* If the editor is an instance of <code>DefaultEditor</code>, the
* call if forwarded to the editor, otherwise this does nothing.
*
* @throws ParseException if the currently edited value couldn't
* be committed.
*/
publicvoidcommitEdit() throwsParseException {
JComponenteditor = getEditor();
if (editorinstanceofDefaultEditor) {
((DefaultEditor)editor).commitEdit();
}
}
/*
* See readObject and writeObject in JComponent for more
* information about serialization in Swing.
*
* @param s Stream to write to
*/
@Serial
privatevoidwriteObject(ObjectOutputStreams) throwsIOException {
s.defaultWriteObject();
if (getUIClassID().equals(uiClassID)) {
bytecount = JComponent.getWriteObjCounter(this);
JComponent.setWriteObjCounter(this, --count);
if (count == 0 && ui != null) {
ui.installUI(this);
}
}
}
/**
* A simple base class for more specialized editors
* that displays a read-only view of the model's current
* value with a <code>JFormattedTextField</code>. Subclasses
* can configure the <code>JFormattedTextField</code> to create
* an editor that's appropriate for the type of model they
* support and they may want to override
* the <code>stateChanged</code> and <code>propertyChanged</code>
* methods, which keep the model and the text field in sync.
* <p>
* This class defines a <code>dismiss</code> method that removes the
* editors <code>ChangeListener</code> from the <code>JSpinner</code>
* that it's part of. The <code>setEditor</code> method knows about
* <code>DefaultEditor.dismiss</code>, so if the developer
* replaces an editor that's derived from <code>JSpinner.DefaultEditor</code>
* its <code>ChangeListener</code> connection back to the
* <code>JSpinner</code> will be removed. However after that,
* it's up to the developer to manage their editor listeners.
* Similarly, if a subclass overrides <code>createEditor</code>,
* it's up to the subclasser to deal with their editor
* subsequently being replaced (with <code>setEditor</code>).
* We expect that in most cases, and in editor installed
* with <code>setEditor</code> or created by a <code>createEditor</code>
* override, will not be replaced anyway.
* <p>
* This class is the <code>LayoutManager</code> for it's single
* <code>JFormattedTextField</code> child. By default the
* child is just centered with the parents insets.
* @since 1.4
*/
publicstaticclassDefaultEditorextendsJPanel
implementsChangeListener, PropertyChangeListener, LayoutManager
{
/**
* Constructs an editor component for the specified <code>JSpinner</code>.
* This <code>DefaultEditor</code> is it's own layout manager and
* it is added to the spinner's <code>ChangeListener</code> list.
* The constructor creates a single <code>JFormattedTextField</code> child,
* initializes it's value to be the spinner model's current value
* and adds it to <code>this</code> <code>DefaultEditor</code>.
*
* @param spinner the spinner whose model <code>this</code> editor will monitor
* @see #getTextField
* @see JSpinner#addChangeListener
*/
publicDefaultEditor(JSpinnerspinner) {
super(null);
JFormattedTextFieldftf = newJFormattedTextField();
ftf.setName("Spinner.formattedTextField");
ftf.setValue(spinner.getValue());
ftf.addPropertyChangeListener(this);
ftf.setEditable(false);
ftf.setInheritsPopupMenu(true);
StringtoolTipText = spinner.getToolTipText();
if (toolTipText != null) {
ftf.setToolTipText(toolTipText);
}
add(ftf);
setLayout(this);
spinner.addChangeListener(this);
// We want the spinner's increment/decrement actions to be
// active vs those of the JFormattedTextField. As such we
// put disabled actions in the JFormattedTextField's actionmap.
// A binding to a disabled action is treated as a non-existent
// binding.
ActionMapftfMap = ftf.getActionMap();
if (ftfMap != null) {
ftfMap.put("increment", DISABLED_ACTION);
ftfMap.put("decrement", DISABLED_ACTION);
}
}
/**
* Disconnect <code>this</code> editor from the specified
* <code>JSpinner</code>. By default, this method removes
* itself from the spinners <code>ChangeListener</code> list.
*
* @param spinner the <code>JSpinner</code> to disconnect this
* editor from; the same spinner as was passed to the constructor.
*/
publicvoiddismiss(JSpinnerspinner) {
spinner.removeChangeListener(this);
}
/**
* Returns the <code>JSpinner</code> ancestor of this editor or
* <code>null</code> if none of the ancestors are a
* <code>JSpinner</code>.
* Typically the editor's parent is a <code>JSpinner</code> however
* subclasses of <code>JSpinner</code> may override the
* the <code>createEditor</code> method and insert one or more containers
* between the <code>JSpinner</code> and it's editor.
*
* @return <code>JSpinner</code> ancestor; <code>null</code>
* if none of the ancestors are a <code>JSpinner</code>
*
* @see JSpinner#createEditor
*/
publicJSpinnergetSpinner() {
for (Componentc = this; c != null; c = c.getParent()) {
if (cinstanceofJSpinner) {
return (JSpinner)c;
}
}
returnnull;
}
/**
* Returns the <code>JFormattedTextField</code> child of this
* editor. By default the text field is the first and only
* child of editor.
*
* @return the <code>JFormattedTextField</code> that gives the user
* access to the <code>SpinnerDateModel's</code> value.
* @see #getSpinner
* @see #getModel
*/
publicJFormattedTextFieldgetTextField() {
return (JFormattedTextField)getComponent(0);
}
/**
* This method is called when the spinner's model's state changes.
* It sets the <code>value</code> of the text field to the current
* value of the spinners model.
*
* @param e the <code>ChangeEvent</code> whose source is the
* <code>JSpinner</code> whose model has changed.
* @see #getTextField
* @see JSpinner#getValue
*/
publicvoidstateChanged(ChangeEvente) {
JSpinnerspinner = (JSpinner)(e.getSource());
getTextField().setValue(spinner.getValue());
}
/**
* Called by the <code>JFormattedTextField</code>
* <code>PropertyChangeListener</code>. When the <code>"value"</code>
* property changes, which implies that the user has typed a new
* number, we set the value of the spinners model.
* <p>
* This class ignores <code>PropertyChangeEvents</code> whose
* source is not the <code>JFormattedTextField</code>, so subclasses
* may safely make <code>this</code> <code>DefaultEditor</code> a
* <code>PropertyChangeListener</code> on other objects.
*
* @param e the <code>PropertyChangeEvent</code> whose source is
* the <code>JFormattedTextField</code> created by this class.
* @see #getTextField
*/
publicvoidpropertyChange(PropertyChangeEvente)
{
JSpinnerspinner = getSpinner();
if (spinner == null) {
// Indicates we aren't installed anywhere.
return;
}
Objectsource = e.getSource();
Stringname = e.getPropertyName();
if (sourceinstanceofJFormattedTextField) {
if ("value".equals(name)) {
ObjectlastValue = spinner.getValue();
// Try to set the new value
try {
spinner.setValue(getTextField().getValue());
} catch (IllegalArgumentExceptioniae) {
// SpinnerModel didn't like new value, reset
try {
((JFormattedTextField)source).setValue(lastValue);
} catch (IllegalArgumentExceptioniae2) {
// Still bogus, nothing else we can do, the
// SpinnerModel and JFormattedTextField are now out
// of sync.
}
}
} elseif ("font".equals(name)) {
Objectnewfont = e.getNewValue();
if (newfontinstanceofUIResource) {
// The text field font must match the JSpinner font if
// the text field font was not set by the user
Fontfont = spinner.getFont();
if (!newfont.equals(font)) {
getTextField().setFont(font == null ? null : newFontUIResource(font));
}
}
}
}
}
/**
* This <code>LayoutManager</code> method does nothing. We're
* only managing a single child and there's no support
* for layout constraints.
*
* @param name ignored
* @param child ignored
*/
publicvoidaddLayoutComponent(Stringname, Componentchild) {
}
/**
* This <code>LayoutManager</code> method does nothing. There
* isn't any per-child state.
*
* @param child ignored
*/
publicvoidremoveLayoutComponent(Componentchild) {
}
/**
* Returns the size of the parents insets.
*/
privateDimensioninsetSize(Containerparent) {
Insetsinsets = parent.getInsets();
intw = insets.left + insets.right;
inth = insets.top + insets.bottom;
returnnewDimension(w, h);
}
/**
* Returns the preferred size of first (and only) child plus the
* size of the parents insets.
*
* @param parent the Container that's managing the layout
* @return the preferred dimensions to lay out the subcomponents
* of the specified container.
*/
publicDimensionpreferredLayoutSize(Containerparent) {
DimensionpreferredSize = insetSize(parent);
if (parent.getComponentCount() > 0) {
DimensionchildSize = getComponent(0).getPreferredSize();
preferredSize.width += childSize.width;
preferredSize.height += childSize.height;
}
returnpreferredSize;
}
/**
* Returns the minimum size of first (and only) child plus the
* size of the parents insets.
*
* @param parent the Container that's managing the layout
* @return the minimum dimensions needed to lay out the subcomponents
* of the specified container.
*/
publicDimensionminimumLayoutSize(Containerparent) {
DimensionminimumSize = insetSize(parent);
if (parent.getComponentCount() > 0) {
DimensionchildSize = getComponent(0).getMinimumSize();
minimumSize.width += childSize.width;
minimumSize.height += childSize.height;
}
returnminimumSize;
}
/**
* Resize the one (and only) child to completely fill the area
* within the parents insets.
*/
publicvoidlayoutContainer(Containerparent) {
if (parent.getComponentCount() > 0) {
Insetsinsets = parent.getInsets();
intw = parent.getWidth() - (insets.left + insets.right);
inth = parent.getHeight() - (insets.top + insets.bottom);
getComponent(0).setBounds(insets.left, insets.top, w, h);
}
}
/**
* Pushes the currently edited value to the <code>SpinnerModel</code>.
* <p>
* The default implementation invokes <code>commitEdit</code> on the
* <code>JFormattedTextField</code>.
*
* @throws ParseException if the edited value is not legal
*/
publicvoidcommitEdit() throwsParseException {
// If the value in the JFormattedTextField is legal, this will have
// the result of pushing the value to the SpinnerModel
// by way of the <code>propertyChange</code> method.
JFormattedTextFieldftf = getTextField();
ftf.commitEdit();
}
/**
* Returns the baseline.
*
* @throws IllegalArgumentException {@inheritDoc}
* @see javax.swing.JComponent#getBaseline(int,int)
* @see javax.swing.JComponent#getBaselineResizeBehavior()
* @since 1.6
*/
publicintgetBaseline(intwidth, intheight) {
// check size.
super.getBaseline(width, height);
Insetsinsets = getInsets();
width = width - insets.left - insets.right;
height = height - insets.top - insets.bottom;
intbaseline = getComponent(0).getBaseline(width, height);
if (baseline >= 0) {
returnbaseline + insets.top;
}
return -1;
}
/**
* Returns an enum indicating how the baseline of the component
* changes as the size changes.
*
* @see javax.swing.JComponent#getBaseline(int, int)
* @since 1.6
*/
publicBaselineResizeBehaviorgetBaselineResizeBehavior() {
returngetComponent(0).getBaselineResizeBehavior();
}
}
/**
* This subclass of javax.swing.DateFormatter maps the minimum/maximum
* properties to the start/end properties of a SpinnerDateModel.
*/
privatestaticclassDateEditorFormatterextendsDateFormatter {
privatefinalSpinnerDateModelmodel;
DateEditorFormatter(SpinnerDateModelmodel, DateFormatformat) {
super(format);
this.model = model;
}
@Override
@SuppressWarnings("unchecked")
publicvoidsetMinimum(Comparable<?> min) {
model.setStart((Comparable<Date>)min);
}
@Override
publicComparable<Date> getMinimum() {
returnmodel.getStart();
}
@Override
@SuppressWarnings("unchecked")
publicvoidsetMaximum(Comparable<?> max) {
model.setEnd((Comparable<Date>)max);
}
@Override
publicComparable<Date> getMaximum() {
returnmodel.getEnd();
}
}
/**
* An editor for a <code>JSpinner</code> whose model is a
* <code>SpinnerDateModel</code>. The value of the editor is
* displayed with a <code>JFormattedTextField</code> whose format
* is defined by a <code>DateFormatter</code> instance whose
* <code>minimum</code> and <code>maximum</code> properties
* are mapped to the <code>SpinnerDateModel</code>.
* @since 1.4
*/
// PENDING(hmuller): more example javadoc
publicstaticclassDateEditorextendsDefaultEditor
{
// This is here until SimpleDateFormat gets a constructor that
// takes a Locale: 4923525
privatestaticStringgetDefaultPattern(Localeloc) {
LocaleProviderAdapteradapter = LocaleProviderAdapter.getAdapter(DateFormatProvider.class, loc);