- Notifications
You must be signed in to change notification settings - Fork 5.8k
/
Copy pathJTextComponent.java
5103 lines (4705 loc) · 189 KB
/
JTextComponent.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) 1997, 2024, 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.text;
importcom.sun.beans.util.Cache;
importjava.beans.JavaBean;
importjava.beans.BeanProperty;
importjava.beans.Transient;
importjava.util.ArrayList;
importjava.util.HashMap;
importjava.util.Hashtable;
importjava.util.Enumeration;
importjava.util.concurrent.*;
importjava.io.*;
importjava.awt.*;
importjava.awt.event.*;
importjava.awt.print.*;
importjava.awt.datatransfer.*;
importjava.awt.im.InputContext;
importjava.awt.im.InputMethodRequests;
importjava.awt.font.TextHitInfo;
importjava.awt.font.TextAttribute;
importjava.awt.geom.Point2D;
importjava.awt.geom.Rectangle2D;
importjavax.print.PrintService;
importjava.text.*;
importjava.text.AttributedCharacterIterator.Attribute;
importjavax.swing.*;
importjavax.swing.event.*;
importjavax.swing.plaf.*;
importjavax.accessibility.*;
importjavax.print.attribute.*;
importsun.awt.AppContext;
importsun.swing.PrintingStatus;
importsun.swing.SwingUtilities2;
importsun.swing.text.TextComponentPrintable;
importsun.swing.SwingAccessor;
/**
* <code>JTextComponent</code> is the base class for swing text
* components. It tries to be compatible with the
* <code>java.awt.TextComponent</code> class
* where it can reasonably do so. Also provided are other services
* for additional flexibility (beyond the pluggable UI and bean
* support).
* You can find information on how to use the functionality
* this class provides in
* <a href="https://docs.oracle.com/javase/tutorial/uiswing/components/generaltext.html">General Rules for Using Text Components</a>,
* a section in <em>The Java Tutorial.</em>
*
* <dl>
* <dt><b>Caret Changes</b>
* <dd>
* The caret is a pluggable object in swing text components.
* Notification of changes to the caret position and the selection
* are sent to implementations of the <code>CaretListener</code>
* interface that have been registered with the text component.
* The UI will install a default caret unless a customized caret
* has been set. <br>
* By default the caret tracks all the document changes
* performed on the Event Dispatching Thread and updates it's position
* accordingly if an insertion occurs before or at the caret position
* or a removal occurs before the caret position. <code>DefaultCaret</code>
* tries to make itself visible which may lead to scrolling
* of a text component within <code>JScrollPane</code>. The default caret
* behavior can be changed by the {@link DefaultCaret#setUpdatePolicy} method.
* <br>
* <b>Note</b>: Non-editable text components also have a caret though
* it may not be painted.
*
* <dt><b>Commands</b>
* <dd>
* Text components provide a number of commands that can be used
* to manipulate the component. This is essentially the way that
* the component expresses its capabilities. These are expressed
* in terms of the swing <code>Action</code> interface,
* using the <code>TextAction</code> implementation.
* The set of commands supported by the text component can be
* found with the {@link #getActions} method. These actions
* can be bound to key events, fired from buttons, etc.
*
* <dt><b>Text Input</b>
* <dd>
* The text components support flexible and internationalized text input, using
* keymaps and the input method framework, while maintaining compatibility with
* the AWT listener model.
* <p>
* A {@link javax.swing.text.Keymap} lets an application bind key
* strokes to actions.
* In order to allow keymaps to be shared across multiple text components, they
* can use actions that extend <code>TextAction</code>.
* <code>TextAction</code> can determine which <code>JTextComponent</code>
* most recently has or had focus and therefore is the subject of
* the action (In the case that the <code>ActionEvent</code>
* sent to the action doesn't contain the target text component as its source).
* <p>
* The {@extLink imf_overview Input Method Framework}
* lets text components interact with input methods, separate software
* components that preprocess events to let users enter thousands of
* different characters using keyboards with far fewer keys.
* <code>JTextComponent</code> is an <em>active client</em> of
* the framework, so it implements the preferred user interface for interacting
* with input methods. As a consequence, some key events do not reach the text
* component because they are handled by an input method, and some text input
* reaches the text component as committed text within an {@link
* java.awt.event.InputMethodEvent} instead of as a key event.
* The complete text input is the combination of the characters in
* <code>keyTyped</code> key events and committed text in input method events.
* <p>
* The AWT listener model lets applications attach event listeners to
* components in order to bind events to actions. Swing encourages the
* use of keymaps instead of listeners, but maintains compatibility
* with listeners by giving the listeners a chance to steal an event
* by consuming it.
* <p>
* Keyboard event and input method events are handled in the following stages,
* with each stage capable of consuming the event:
*
* <table class="striped">
* <caption>Stages of keyboard and input method event handling</caption>
* <thead>
* <tr>
* <th scope="col">Stage
* <th scope="col">KeyEvent
* <th scope="col">InputMethodEvent
* </thead>
* <tbody>
* <tr>
* <th scope="row">1.
* <td>input methods
* <td>(generated here)
* <tr>
* <th scope="row">2.
* <td>focus manager
* <td>
* </tr>
* <tr>
* <th scope="row">3.
* <td>registered key listeners
* <td>registered input method listeners
* <tr>
* <th scope="row">4.
* <td>
* <td>input method handling in JTextComponent
* <tr>
* <th scope="row">5.
* <td colspan=2>keymap handling using the current keymap
* <tr>
* <th scope="row">6.
* <td>keyboard handling in JComponent (e.g. accelerators, component
* navigation, etc.)
* <td>
* </tbody>
* </table>
* <p>
* To maintain compatibility with applications that listen to key
* events but are not aware of input method events, the input
* method handling in stage 4 provides a compatibility mode for
* components that do not process input method events. For these
* components, the committed text is converted to keyTyped key events
* and processed in the key event pipeline starting at stage 3
* instead of in the input method event pipeline.
* <p>
* By default the component will create a keymap (named <b>DEFAULT_KEYMAP</b>)
* that is shared by all JTextComponent instances as the default keymap.
* Typically a look-and-feel implementation will install a different keymap
* that resolves to the default keymap for those bindings not found in the
* different keymap. The minimal bindings include:
* <ul>
* <li>inserting content into the editor for the
* printable keys.
* <li>removing content with the backspace and del
* keys.
* <li>caret movement forward and backward
* </ul>
*
* <dt><b>Model/View Split</b>
* <dd>
* The text components have a model-view split. A text component pulls
* together the objects used to represent the model, view, and controller.
* The text document model may be shared by other views which act as observers
* of the model (e.g. a document may be shared by multiple components).
*
* <p style="text-align:center"><img src="doc-files/editor.gif" alt="Diagram showing interaction between Controller, Document, events, and ViewFactory"
* HEIGHT=358 WIDTH=587></p>
*
* <p>
* The model is defined by the {@link Document} interface.
* This is intended to provide a flexible text storage mechanism
* that tracks change during edits and can be extended to more sophisticated
* models. The model interfaces are meant to capture the capabilities of
* expression given by SGML, a system used to express a wide variety of
* content.
* Each modification to the document causes notification of the
* details of the change to be sent to all observers in the form of a
* {@link DocumentEvent} which allows the views to stay up to date with the model.
* This event is sent to observers that have implemented the
* {@link DocumentListener}
* interface and registered interest with the model being observed.
*
* <dt><b>Location Information</b>
* <dd>
* The capability of determining the location of text in
* the view is provided. There are two methods, {@link #modelToView}
* and {@link #viewToModel} for determining this information.
*
* <dt><b>Undo/Redo support</b>
* <dd>
* Support for an edit history mechanism is provided to allow
* undo/redo operations. The text component does not itself
* provide the history buffer by default, but does provide
* the <code>UndoableEdit</code> records that can be used in conjunction
* with a history buffer to provide the undo/redo support.
* The support is provided by the Document model, which allows
* one to attach UndoableEditListener implementations.
*
* <dt><b>Thread Safety</b>
* <dd>
* The swing text components provide some support of thread
* safe operations. Because of the high level of configurability
* of the text components, it is possible to circumvent the
* protection provided. The protection primarily comes from
* the model, so the documentation of <code>AbstractDocument</code>
* describes the assumptions of the protection provided.
* The methods that are safe to call asynchronously are marked
* with comments.
*
* <dt><b>Newlines</b>
* <dd>
* For a discussion on how newlines are handled, see
* <a href="DefaultEditorKit.html">DefaultEditorKit</a>.
*
*
* <dt><b>Printing support</b>
* <dd>
* Several {@link #print print} methods are provided for basic
* document printing. If more advanced printing is needed, use the
* {@link #getPrintable} method.
* </dl>
*
* <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}.
*
* @author Timothy Prinzing
* @author Igor Kushnirskiy (printing support)
* @see Document
* @see DocumentEvent
* @see DocumentListener
* @see Caret
* @see CaretEvent
* @see CaretListener
* @see TextUI
* @see View
* @see ViewFactory
*/
@JavaBean(defaultProperty = "UI")
@SwingContainer(false)
@SuppressWarnings("serial") // Same-version serialization only
publicabstractclassJTextComponentextendsJComponentimplementsScrollable, Accessible
{
/**
* Creates a new <code>JTextComponent</code>.
* Listeners for caret events are established, and the pluggable
* UI installed. The component is marked as editable. No layout manager
* is used, because layout is managed by the view subsystem of text.
* The document model is set to <code>null</code>.
*/
publicJTextComponent() {
super();
// enable InputMethodEvent for on-the-spot pre-editing
enableEvents(AWTEvent.KEY_EVENT_MASK | AWTEvent.INPUT_METHOD_EVENT_MASK);
caretEvent = newMutableCaretEvent(this);
addMouseListener(caretEvent);
addFocusListener(caretEvent);
setEditable(true);
setDragEnabled(false);
setLayout(null); // layout is managed by View hierarchy
updateUI();
}
/**
* Fetches the user-interface factory for this text-oriented editor.
*
* @return the factory
*/
publicTextUIgetUI() { return (TextUI)ui; }
/**
* Sets the user-interface factory for this text-oriented editor.
*
* @param ui the factory
*/
publicvoidsetUI(TextUIui) {
super.setUI(ui);
}
/**
* Reloads the pluggable UI. The key used to fetch the
* new interface is <code>getUIClassID()</code>. The type of
* the UI is <code>TextUI</code>. <code>invalidate</code>
* is called after setting the UI.
*/
publicvoidupdateUI() {
setUI((TextUI)UIManager.getUI(this));
invalidate();
}
/**
* Adds a caret listener for notification of any changes
* to the caret.
*
* @param listener the listener to be added
* @see javax.swing.event.CaretEvent
*/
publicvoidaddCaretListener(CaretListenerlistener) {
listenerList.add(CaretListener.class, listener);
}
/**
* Removes a caret listener.
*
* @param listener the listener to be removed
* @see javax.swing.event.CaretEvent
*/
publicvoidremoveCaretListener(CaretListenerlistener) {
listenerList.remove(CaretListener.class, listener);
}
/**
* Returns an array of all the caret listeners
* registered on this text component.
*
* @return all of this component's <code>CaretListener</code>s
* or an empty
* array if no caret listeners are currently registered
*
* @see #addCaretListener
* @see #removeCaretListener
*
* @since 1.4
*/
@BeanProperty(bound = false)
publicCaretListener[] getCaretListeners() {
returnlistenerList.getListeners(CaretListener.class);
}
/**
* Notifies all listeners that have registered interest for
* notification on this event type. The event instance
* is lazily created using the parameters passed into
* the fire method. The listener list is processed in a
* last-to-first manner.
*
* @param e the event
* @see EventListenerList
*/
protectedvoidfireCaretUpdate(CaretEvente) {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (inti = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==CaretListener.class) {
((CaretListener)listeners[i+1]).caretUpdate(e);
}
}
}
/**
* Associates the editor with a text document.
* The currently registered factory is used to build a view for
* the document, which gets displayed by the editor after revalidation.
* A PropertyChange event ("document") is propagated to each listener.
*
* @param doc the document to display/edit
* @see #getDocument
*/
@BeanProperty(expert = true, description
= "the text document model")
publicvoidsetDocument(Documentdoc) {
Documentold = model;
/*
* acquire a read lock on the old model to prevent notification of
* mutations while we disconnecting the old model.
*/
try {
if (oldinstanceofAbstractDocument) {
((AbstractDocument)old).readLock();
}
if (accessibleContext != null) {
model.removeDocumentListener(
((AccessibleJTextComponent)accessibleContext));
}
if (inputMethodRequestsHandler != null) {
model.removeDocumentListener((DocumentListener)inputMethodRequestsHandler);
}
model = doc;
// Set the document's run direction property to match the
// component's ComponentOrientation property.
BooleanrunDir = getComponentOrientation().isLeftToRight()
? TextAttribute.RUN_DIRECTION_LTR
: TextAttribute.RUN_DIRECTION_RTL;
if (runDir != doc.getProperty(TextAttribute.RUN_DIRECTION)) {
doc.putProperty(TextAttribute.RUN_DIRECTION, runDir );
}
firePropertyChange("document", old, doc);
} finally {
if (oldinstanceofAbstractDocument) {
((AbstractDocument)old).readUnlock();
}
}
revalidate();
repaint();
if (accessibleContext != null) {
model.addDocumentListener(
((AccessibleJTextComponent)accessibleContext));
}
if (inputMethodRequestsHandler != null) {
model.addDocumentListener((DocumentListener)inputMethodRequestsHandler);
}
}
/**
* Fetches the model associated with the editor. This is
* primarily for the UI to get at the minimal amount of
* state required to be a text editor. Subclasses will
* return the actual type of the model which will typically
* be something that extends Document.
*
* @return the model
*/
publicDocumentgetDocument() {
returnmodel;
}
// Override of Component.setComponentOrientation
publicvoidsetComponentOrientation( ComponentOrientationo ) {
// Set the document's run direction property to match the
// ComponentOrientation property.
Documentdoc = getDocument();
if( doc != null ) {
BooleanrunDir = o.isLeftToRight()
? TextAttribute.RUN_DIRECTION_LTR
: TextAttribute.RUN_DIRECTION_RTL;
doc.putProperty( TextAttribute.RUN_DIRECTION, runDir );
}
super.setComponentOrientation( o );
}
/**
* Fetches the command list for the editor. This is
* the list of commands supported by the plugged-in UI
* augmented by the collection of commands that the
* editor itself supports. These are useful for binding
* to events, such as in a keymap.
*
* @return the command list
*/
@BeanProperty(bound = false)
publicAction[] getActions() {
returngetUI().getEditorKit(this).getActions();
}
/**
* Sets margin space between the text component's border
* and its text. The text component's default <code>Border</code>
* object will use this value to create the proper margin.
* However, if a non-default border is set on the text component,
* it is that <code>Border</code> object's responsibility to create the
* appropriate margin space (else this property will effectively
* be ignored). This causes a redraw of the component.
* A PropertyChange event ("margin") is sent to all listeners.
*
* @param m the space between the border and the text
*/
@BeanProperty(description
= "desired space between the border and text area")
publicvoidsetMargin(Insetsm) {
Insetsold = margin;
margin = m;
firePropertyChange("margin", old, m);
invalidate();
}
/**
* Returns the margin between the text component's border and
* its text.
*
* @return the margin
*/
publicInsetsgetMargin() {
returnmargin;
}
/**
* Sets the <code>NavigationFilter</code>. <code>NavigationFilter</code>
* is used by <code>DefaultCaret</code> and the default cursor movement
* actions as a way to restrict the cursor movement.
* @param filter the filter
*
* @since 1.4
*/
publicvoidsetNavigationFilter(NavigationFilterfilter) {
navigationFilter = filter;
}
/**
* Returns the <code>NavigationFilter</code>. <code>NavigationFilter</code>
* is used by <code>DefaultCaret</code> and the default cursor movement
* actions as a way to restrict the cursor movement. A null return value
* implies the cursor movement and selection should not be restricted.
*
* @since 1.4
* @return the NavigationFilter
*/
publicNavigationFiltergetNavigationFilter() {
returnnavigationFilter;
}
/**
* Fetches the caret that allows text-oriented navigation over
* the view.
*
* @return the caret
*/
@Transient
publicCaretgetCaret() {
returncaret;
}
/**
* Sets the caret to be used. By default this will be set
* by the UI that gets installed. This can be changed to
* a custom caret if desired. Setting the caret results in a
* PropertyChange event ("caret") being fired.
*
* @param c the caret
* @see #getCaret
*/
@BeanProperty(expert = true, description
= "the caret used to select/navigate")
publicvoidsetCaret(Caretc) {
if (caret != null) {
caret.removeChangeListener(caretEvent);
caret.deinstall(this);
}
Caretold = caret;
caret = c;
if (caret != null) {
caret.install(this);
caret.addChangeListener(caretEvent);
}
firePropertyChange("caret", old, caret);
}
/**
* Fetches the object responsible for making highlights.
*
* @return the highlighter
*/
publicHighlightergetHighlighter() {
returnhighlighter;
}
/**
* Sets the highlighter to be used. By default this will be set
* by the UI that gets installed. This can be changed to
* a custom highlighter if desired. The highlighter can be set to
* <code>null</code> to disable it.
* A PropertyChange event ("highlighter") is fired
* when a new highlighter is installed.
*
* @param h the highlighter
* @see #getHighlighter
*/
@BeanProperty(expert = true, description
= "object responsible for background highlights")
publicvoidsetHighlighter(Highlighterh) {
if (highlighter != null) {
highlighter.deinstall(this);
}
Highlighterold = highlighter;
highlighter = h;
if (highlighter != null) {
highlighter.install(this);
}
firePropertyChange("highlighter", old, h);
}
/**
* Sets the keymap to use for binding events to
* actions. Setting to <code>null</code> effectively disables
* keyboard input.
* A PropertyChange event ("keymap") is fired when a new keymap
* is installed.
*
* @param map the keymap
* @see #getKeymap
*/
@BeanProperty(description
= "set of key event to action bindings to use")
publicvoidsetKeymap(Keymapmap) {
Keymapold = keymap;
keymap = map;
firePropertyChange("keymap", old, keymap);
updateInputMap(old, map);
}
/**
* Turns on or off automatic drag handling. In order to enable automatic
* drag handling, this property should be set to {@code true}, and the
* component's {@code TransferHandler} needs to be {@code non-null}.
* The default value of the {@code dragEnabled} property is {@code false}.
* <p>
* The job of honoring this property, and recognizing a user drag gesture,
* lies with the look and feel implementation, and in particular, the component's
* {@code TextUI}. When automatic drag handling is enabled, most look and
* feels (including those that subclass {@code BasicLookAndFeel}) begin a
* drag and drop operation whenever the user presses the mouse button over
* a selection and then moves the mouse a few pixels. Setting this property to
* {@code true} can therefore have a subtle effect on how selections behave.
* <p>
* If a look and feel is used that ignores this property, you can still
* begin a drag and drop operation by calling {@code exportAsDrag} on the
* component's {@code TransferHandler}.
*
* @param b whether or not to enable automatic drag handling
* @throws HeadlessException if
* <code>b</code> is <code>true</code> and
* <code>GraphicsEnvironment.isHeadless()</code>
* returns <code>true</code>
* @see java.awt.GraphicsEnvironment#isHeadless
* @see #getDragEnabled
* @see #setTransferHandler
* @see TransferHandler
* @since 1.4
*/
@BeanProperty(bound = false, description
= "determines whether automatic drag handling is enabled")
publicvoidsetDragEnabled(booleanb) {
checkDragEnabled(b);
dragEnabled = b;
}
privatestaticvoidcheckDragEnabled(booleanb) {
if (b && GraphicsEnvironment.isHeadless()) {
thrownewHeadlessException();
}
}
/**
* Returns whether or not automatic drag handling is enabled.
*
* @return the value of the {@code dragEnabled} property
* @see #setDragEnabled
* @since 1.4
*/
publicbooleangetDragEnabled() {
returndragEnabled;
}
/**
* Sets the drop mode for this component. For backward compatibility,
* the default for this property is <code>DropMode.USE_SELECTION</code>.
* Usage of <code>DropMode.INSERT</code> is recommended, however,
* for an improved user experience. It offers similar behavior of dropping
* between text locations, but does so without affecting the actual text
* selection and caret location.
* <p>
* <code>JTextComponents</code> support the following drop modes:
* <ul>
* <li><code>DropMode.USE_SELECTION</code></li>
* <li><code>DropMode.INSERT</code></li>
* </ul>
* <p>
* The drop mode is only meaningful if this component has a
* <code>TransferHandler</code> that accepts drops.
*
* @param dropMode the drop mode to use
* @throws IllegalArgumentException if the drop mode is unsupported
* or <code>null</code>
* @see #getDropMode
* @see #getDropLocation
* @see #setTransferHandler
* @see javax.swing.TransferHandler
* @since 1.6
*/
publicfinalvoidsetDropMode(DropModedropMode) {
checkDropMode(dropMode);
this.dropMode = dropMode;
}
privatestaticvoidcheckDropMode(DropModedropMode) {
if (dropMode != null) {
switch (dropMode) {
caseUSE_SELECTION:
caseINSERT:
return;
}
}
thrownewIllegalArgumentException(dropMode + ": Unsupported drop mode for text");
}
/**
* Returns the drop mode for this component.
*
* @return the drop mode for this component
* @see #setDropMode
* @since 1.6
*/
publicfinalDropModegetDropMode() {
returndropMode;
}
static {
SwingAccessor.setJTextComponentAccessor(
newSwingAccessor.JTextComponentAccessor() {
publicTransferHandler.DropLocationdropLocationForPoint(JTextComponenttextComp,
Pointp)
{
returntextComp.dropLocationForPoint(p);
}
publicObjectsetDropLocation(JTextComponenttextComp,
TransferHandler.DropLocationlocation,
Objectstate, booleanforDrop)
{
returntextComp.setDropLocation(location, state, forDrop);
}
});
}
/**
* Calculates a drop location in this component, representing where a
* drop at the given point should insert data.
* <p>
* Note: This method is meant to override
* <code>JComponent.dropLocationForPoint()</code>, which is package-private
* in javax.swing. <code>TransferHandler</code> will detect text components
* and call this method instead via reflection. It's name should therefore
* not be changed.
*
* @param p the point to calculate a drop location for
* @return the drop location, or <code>null</code>
*/
@SuppressWarnings("deprecation")
DropLocationdropLocationForPoint(Pointp) {
Position.Bias[] bias = newPosition.Bias[1];
intindex = getUI().viewToModel(this, p, bias);
// viewToModel currently returns null for some HTML content
// when the point is within the component's top inset
if (bias[0] == null) {
bias[0] = Position.Bias.Forward;
}
returnnewDropLocation(p, index, bias[0]);
}
/**
* Called to set or clear the drop location during a DnD operation.
* In some cases, the component may need to use it's internal selection
* temporarily to indicate the drop location. To help facilitate this,
* this method returns and accepts as a parameter a state object.
* This state object can be used to store, and later restore, the selection
* state. Whatever this method returns will be passed back to it in
* future calls, as the state parameter. If it wants the DnD system to
* continue storing the same state, it must pass it back every time.
* Here's how this is used:
* <p>
* Let's say that on the first call to this method the component decides
* to save some state (because it is about to use the selection to show
* a drop index). It can return a state object to the caller encapsulating
* any saved selection state. On a second call, let's say the drop location
* is being changed to something else. The component doesn't need to
* restore anything yet, so it simply passes back the same state object
* to have the DnD system continue storing it. Finally, let's say this
* method is messaged with <code>null</code>. This means DnD
* is finished with this component for now, meaning it should restore
* state. At this point, it can use the state parameter to restore
* said state, and of course return <code>null</code> since there's
* no longer anything to store.
* <p>
* Note: This method is meant to override
* <code>JComponent.setDropLocation()</code>, which is package-private
* in javax.swing. <code>TransferHandler</code> will detect text components
* and call this method instead via reflection. It's name should therefore
* not be changed.
*
* @param location the drop location (as calculated by
* <code>dropLocationForPoint</code>) or <code>null</code>
* if there's no longer a valid drop location
* @param state the state object saved earlier for this component,
* or <code>null</code>
* @param forDrop whether or not the method is being called because an
* actual drop occurred
* @return any saved state for this component, or <code>null</code> if none
*/
ObjectsetDropLocation(TransferHandler.DropLocationlocation,
Objectstate,
booleanforDrop) {
ObjectretVal = null;
DropLocationtextLocation = (DropLocation)location;
if (dropMode == DropMode.USE_SELECTION) {
if (textLocation == null) {
if (state != null) {
/*
* This object represents the state saved earlier.
* If the caret is a DefaultCaret it will be
* an Object array containing, in order:
* - the saved caret mark (Integer)
* - the saved caret dot (Integer)
* - the saved caret visibility (Boolean)
* - the saved mark bias (Position.Bias)
* - the saved dot bias (Position.Bias)
* If the caret is not a DefaultCaret it will
* be similar, but will not contain the dot
* or mark bias.
*/
Object[] vals = (Object[])state;
if (!forDrop) {
if (caretinstanceofDefaultCaret) {
((DefaultCaret)caret).setDot(((Integer)vals[0]).intValue(),
(Position.Bias)vals[3]);
((DefaultCaret)caret).moveDot(((Integer)vals[1]).intValue(),
(Position.Bias)vals[4]);
} else {
caret.setDot(((Integer)vals[0]).intValue());
caret.moveDot(((Integer)vals[1]).intValue());
}
}
caret.setVisible(((Boolean)vals[2]).booleanValue());
}
} else {
if (dropLocation == null) {
booleanvisible;
if (caretinstanceofDefaultCaret) {
DefaultCaretdc = (DefaultCaret)caret;
visible = dc.isActive();
retVal = newObject[] {Integer.valueOf(dc.getMark()),
Integer.valueOf(dc.getDot()),
Boolean.valueOf(visible),
dc.getMarkBias(),
dc.getDotBias()};
} else {
visible = caret.isVisible();
retVal = newObject[] {Integer.valueOf(caret.getMark()),
Integer.valueOf(caret.getDot()),
Boolean.valueOf(visible)};
}
caret.setVisible(true);
} else {
retVal = state;
}
if (caretinstanceofDefaultCaret) {
((DefaultCaret)caret).setDot(textLocation.getIndex(), textLocation.getBias());
} else {
caret.setDot(textLocation.getIndex());
}
}
} else {
if (textLocation == null) {
if (state != null) {
caret.setVisible(((Boolean)state).booleanValue());
}
} else {
if (dropLocation == null) {
booleanvisible = caretinstanceofDefaultCaret
? ((DefaultCaret)caret).isActive()
: caret.isVisible();
retVal = Boolean.valueOf(visible);
caret.setVisible(false);
} else {
retVal = state;
}
}
}
DropLocationold = dropLocation;
dropLocation = textLocation;
firePropertyChange("dropLocation", old, dropLocation);
returnretVal;
}
/**
* Returns the location that this component should visually indicate
* as the drop location during a DnD operation over the component,
* or {@code null} if no location is to currently be shown.
* <p>
* This method is not meant for querying the drop location
* from a {@code TransferHandler}, as the drop location is only
* set after the {@code TransferHandler}'s <code>canImport</code>
* has returned and has allowed for the location to be shown.
* <p>
* When this property changes, a property change event with
* name "dropLocation" is fired by the component.
*
* @return the drop location
* @see #setDropMode
* @see TransferHandler#canImport(TransferHandler.TransferSupport)
* @since 1.6
*/
@BeanProperty(bound = false)
publicfinalDropLocationgetDropLocation() {
returndropLocation;
}
/**
* Updates the <code>InputMap</code>s in response to a
* <code>Keymap</code> change.
* @param oldKm the old <code>Keymap</code>
* @param newKm the new <code>Keymap</code>
*/
voidupdateInputMap(KeymapoldKm, KeymapnewKm) {
// Locate the current KeymapWrapper.
InputMapkm = getInputMap(JComponent.WHEN_FOCUSED);
InputMaplast = km;
while (km != null && !(kminstanceofKeymapWrapper)) {
last = km;
km = km.getParent();
}
if (km != null) {
// Found it, tweak the InputMap that points to it, as well
// as anything it points to.
if (newKm == null) {
if (last != km) {
last.setParent(km.getParent());
}
else {
last.setParent(null);
}
}
else {
InputMapnewKM = newKeymapWrapper(newKm);
last.setParent(newKM);
if (last != km) {
newKM.setParent(km.getParent());
}
}
}
elseif (newKm != null) {
km = getInputMap(JComponent.WHEN_FOCUSED);
if (km != null) {
// Couldn't find it.
// Set the parent of WHEN_FOCUSED InputMap to be the new one.
InputMapnewKM = newKeymapWrapper(newKm);