API Overview API Index Package Overview Direct link to this page
JDK 1.6
  javax.swing.text. JTextComponent View Javadoc
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025

/*
 * @(#)JTextComponent.java	1.229 06/08/03
 *
 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
 * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package javax.swing.text;

import java.lang.reflect.Method;

import java.security.AccessController;
import java.security.PrivilegedAction;

import java.util.Collections;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Enumeration;
import java.util.Vector;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import java.util.concurrent.*;

import java.io.*;

import java.awt.*;
import java.awt.event.*;
import java.awt.print.*;
import java.awt.datatransfer.*;
import java.awt.im.InputContext;
import java.awt.im.InputMethodRequests;
import java.awt.font.TextHitInfo;
import java.awt.font.TextAttribute;

import java.awt.print.Printable;
import java.awt.print.PrinterException;

import javax.print.PrintService;
import javax.print.attribute.PrintRequestAttributeSet;

import java.text.*;
import java.text.AttributedCharacterIterator.Attribute;

import javax.swing.*;
import javax.swing.event.*;
import javax.swing.plaf.*;

import javax.accessibility.*;

import javax.print.attribute.*;

import sun.awt.AppContext;


import sun.swing.PrintingStatus;
import sun.swing.SwingUtilities2;
import sun.swing.text.TextComponentPrintable;

/**
 * <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="http://java.sun.com/docs/books/tutorial/uiswing/components/generaltext.html">General Rules for Using Text Components</a>,
 * a section in <em>The Java Tutorial.</em>
 *
 * <p>
 * <dl>
 * <dt><b><font size=+1>Caret Changes</font></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. 
 *
 * <p>
 * <dt><b><font size=+1>Commands</font></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.
 *
 * <p>
 * <dt><b><font size=+1>Text Input</font></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 <a href="../../../../technotes/guides/imf/spec.html">input method framework</a>
 * 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 border=1 summary="Stages of keyboard and input method event handling">
 * <tr>
 * <th id="stage"><p align="left">Stage</p></th>
 * <th id="ke"><p align="left">KeyEvent</p></th>
 * <th id="ime"><p align="left">InputMethodEvent</p></th></tr>
 * <tr><td headers="stage">1.   </td>
 *     <td headers="ke">input methods </td>
 *     <td headers="ime">(generated here)</td></tr>
 * <tr><td headers="stage">2.   </td>
 *     <td headers="ke">focus manager </td>
 *     <td headers="ime"></td>
 * </tr>
 * <tr>
 *     <td headers="stage">3.   </td>
 *     <td headers="ke">registered key listeners</td>
 *     <td headers="ime">registered input method listeners</tr>
 * <tr>
 *     <td headers="stage">4.   </td>
 *     <td headers="ke"></td>
 *     <td headers="ime">input method handling in JTextComponent</tr>
 * <tr>
 *     <td headers="stage">5.   </td><td headers="ke ime" colspan=2>keymap handling using the current keymap</td></tr>
 * <tr><td headers="stage">6.   </td><td headers="ke">keyboard handling in JComponent (e.g. accelerators, component navigation, etc.)</td>
 *     <td headers="ime"></td></tr>
 * </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>
 *
 * <p>
 * <dt><b><font size=+1>Model/View Split</font></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 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.
 *
 * <p>
 * <dt><b><font size=+1>Location Information</font></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.
 *
 * <p>
 * <dt><b><font size=+1>Undo/Redo support</font></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.
 *
 * <p>
 * <dt><b><font size=+1>Thread Safety</font></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.
 *
 * <p>
 * <dt><b><font size=+1>Newlines</font></b>
 * <dd>
 * For a discussion on how newlines are handled, see
 * <a href="DefaultEditorKit.html">DefaultEditorKit</a>.
 *
 * <p>
 * <dt><b><font size=+1>Printing support</font></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<sup><font size="-2">TM</font></sup>
 * has been added to the <code>java.beans</code> package.
 * Please see {@link java.beans.XMLEncoder}.
 *
 * @beaninfo
 *     attribute: isContainer false
 * 
 * @author  Timothy Prinzing
 * @author Igor Kushnirskiy (printing support)
 * @version 1.229 08/03/06
 * @see Document
 * @see DocumentEvent
 * @see DocumentListener
 * @see Caret
 * @see CaretEvent
 * @see CaretListener
 * @see TextUI
 * @see View
 * @see ViewFactory
 */
public abstract class JTextComponent extends JComponent implements Scrollable, 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>.
     */
    public JTextComponent() {
        super();
	// enable InputMethodEvent for on-the-spot pre-editing
	enableEvents(AWTEvent.KEY_EVENT_MASK | AWTEvent.INPUT_METHOD_EVENT_MASK);
        caretEvent = new MutableCaretEvent(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
     */
    public TextUI getUI() { return (TextUI)ui; }

    /**
     * Sets the user-interface factory for this text-oriented editor.
     *
     * @param ui the factory
     */
    public void setUI(TextUI ui) {
        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.
     */
    public void updateUI() {
        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
     */
    public void addCaretListener(CaretListener listener) {
        listenerList.add(CaretListener.class, listener);
    }

    /**
     * Removes a caret listener.
     *
     * @param listener the listener to be removed
     * @see javax.swing.event.CaretEvent
     */
    public void removeCaretListener(CaretListener listener) {
        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
     */
    public CaretListener[] getCaretListeners() {
        return (CaretListener[])listenerList.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
     */
    protected void fireCaretUpdate(CaretEvent e) {
        // 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 (int i = 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
     * @beaninfo
     *  description: the text document model
     *        bound: true
     *       expert: true
     */
    public void setDocument(Document doc) {
        Document old = model;

	/*
	 * aquire a read lock on the old model to prevent notification of
	 * mutations while we disconnecting the old model.
	 */
	try {
	    if (old instanceof AbstractDocument) {
		((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.
            Boolean runDir = 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 (old instanceof AbstractDocument) {
		((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
     */
    public Document getDocument() {
        return model;
    }

    // Override of Component.setComponentOrientation
    public void setComponentOrientation( ComponentOrientation o ) {
        // Set the document's run direction property to match the
        // ComponentOrientation property.
        Document doc = getDocument();
        if( doc !=  null ) {
            Boolean runDir = 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
     */
    public Action[] getActions() {      
        return getUI().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
     * @beaninfo
     *  description: desired space between the border and text area
     *        bound: true
     */
    public void setMargin(Insets m) {
        Insets old = margin;
        margin = m;
        firePropertyChange("margin", old, m);
        invalidate();
    }

    /**
     * Returns the margin between the text component's border and
     * its text.  
     *
     * @return the margin
     */
    public Insets getMargin() {
        return margin;
    }

    /**
     * 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.
     *
     * @since 1.4
     */
    public void setNavigationFilter(NavigationFilter filter) {
        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
     */
    public NavigationFilter getNavigationFilter() {
        return navigationFilter;
    }

    /**
     * Fetches the caret that allows text-oriented navigation over
     * the view.  
     *
     * @return the caret
     */
    public Caret getCaret() {
        return caret;
    }

    /**
     * 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
     * @beaninfo
     *  description: the caret used to select/navigate
     *        bound: true
     *       expert: true
     */
    public void setCaret(Caret c) {
        if (caret != null) {
            caret.removeChangeListener(caretEvent);
            caret.deinstall(this);
        }
        Caret old = 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
     */
    public Highlighter getHighlighter() {
        return highlighter;
    }

    /**
     * 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
     * @beaninfo
     *  description: object responsible for background highlights
     *        bound: true
     *       expert: true
     */
    public void setHighlighter(Highlighter h) {
        if (highlighter != null) {
            highlighter.deinstall(this);
        }
        Highlighter old = 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
     * @beaninfo
     *  description: set of key event to action bindings to use
     *        bound: true
     */
    public void setKeymap(Keymap map) {
        Keymap old = 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
     * @exception 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
     *
     * @beaninfo
     *  description: determines whether automatic drag handling is enabled
     *        bound: false
     */
    public void setDragEnabled(boolean b) {
        if (b && GraphicsEnvironment.isHeadless()) {
            throw new HeadlessException();
        }
	dragEnabled = b;
    }

    /**
     * Returns whether or not automatic drag handling is enabled.
     *
     * @return the value of the {@code dragEnabled} property
     * @see #setDragEnabled
     * @since 1.4
     */
    public boolean getDragEnabled() {
	return dragEnabled;
    }

    /**
     * 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
     */
    public final void setDropMode(DropMode dropMode) {
        if (dropMode != null) {
            switch (dropMode) {
                case USE_SELECTION:
                case INSERT:
                    this.dropMode = dropMode;
                    return;
            }
        }

        throw new IllegalArgumentException(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
     */
    public final DropMode getDropMode() {
        return dropMode;
    }


    /**
     * 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>
     */
    DropLocation dropLocationForPoint(Point p) {
        Position.Bias[] bias = new Position.Bias[1];
        int index = 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;
        }

        return new DropLocation(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
     */
    Object setDropLocation(TransferHandler.DropLocation location,
                           Object state,
                           boolean forDrop) {

        Object retVal = null;
        DropLocation textLocation = (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 (caret instanceof DefaultCaret) {
                            ((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) {
                    boolean visible;

                    if (caret instanceof DefaultCaret) {
                        DefaultCaret dc = (DefaultCaret)caret;
                        visible = dc.isActive();
                        retVal = new Object[] {Integer.valueOf(dc.getMark()),
                                               Integer.valueOf(dc.getDot()),
                                               Boolean.valueOf(visible),
                                               dc.getMarkBias(),
                                               dc.getDotBias()};
                    } else {
                        visible = caret.isVisible();
                        retVal = new Object[] {Integer.valueOf(caret.getMark()),
                                               Integer.valueOf(caret.getDot()),
                                               Boolean.valueOf(visible)};
                    }

                    caret.setVisible(true);
                } else {
                    retVal = state;
                }

                if (caret instanceof DefaultCaret) {
                    ((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) {
                    boolean visible = caret instanceof DefaultCaret
                                      ? ((DefaultCaret)caret).isActive()
                                      : caret.isVisible();
                    retVal = Boolean.valueOf(visible);
                    caret.setVisible(false);
                } else {
                    retVal = state;
                }
            }
        }

        DropLocation old = dropLocation;
        dropLocation = textLocation;
        firePropertyChange("dropLocation", old, dropLocation);

        return retVal;
    }

    /**
     * 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
     */
    public final DropLocation getDropLocation() {
        return dropLocation;
    }


    /**
     * 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>
     */
    void updateInputMap(Keymap oldKm, Keymap newKm) {
	// Locate the current KeymapWrapper.
	InputMap km = getInputMap(JComponent.WHEN_FOCUSED);
	InputMap last = km;
	while (km != null && !(km instanceof KeymapWrapper)) {
	    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 {
		InputMap newKM = new KeymapWrapper(newKm);
		last.setParent(newKM);
		if (last != km) {
		    newKM.setParent(km.getParent());
		}
	    }
	}
	else if (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.
		InputMap newKM = new KeymapWrapper(newKm);
		newKM.setParent(km.getParent());
		km.setParent(newKM);
	    }
	}

	// Do the same thing with the ActionMap
	ActionMap am = getActionMap();
	ActionMap lastAM = am;
	while (am != null && !(am instanceof KeymapActionMap)) {
	    lastAM = am;
	    am = am.getParent();
	}
	if (am != null) {
	    // Found it, tweak the Actionap that points to it, as well
	    // as anything it points to.
	    if (newKm == null) {
		if (lastAM != am) {
		    lastAM.setParent(am.getParent());
		}
		else {
		    lastAM.setParent(null);
		}
	    }
	    else {
		ActionMap newAM = new KeymapActionMap(newKm);
		lastAM.setParent(newAM);
		if (lastAM != am) {
		    newAM.setParent(am.getParent());
		}
	    }
	}
	else if (newKm != null) {
	    am = getActionMap();
	    if (am != null) {
		// Couldn't find it.
		// Set the parent of ActionMap to be the new one.
		ActionMap newAM = new KeymapActionMap(newKm);
		newAM.setParent(am.getParent());
		am.setParent(newAM);
	    }
	}
    }

    /**
     * Fetches the keymap currently active in this text
     * component.
     *
     * @return the keymap
     */
    public Keymap getKeymap() {
        return keymap;
    }

    /**
     * Adds a new keymap into the keymap hierarchy.  Keymap bindings
     * resolve from bottom up so an attribute specified in a child
     * will override an attribute specified in the parent.
     *
     * @param nm   the name of the keymap (must be unique within the
     *   collection of named keymaps in the document); the name may 
     *   be <code>null</code> if the keymap is unnamed,
     *   but the caller is responsible for managing the reference
     *   returned as an unnamed keymap can't
     *   be fetched by name
     * @param parent the parent keymap; this may be <code>null</code> if
     *   unspecified bindings need not be resolved in some other keymap
     * @return the keymap
     */
    public static Keymap addKeymap(String nm, Keymap parent) {
        Keymap map = new DefaultKeymap(nm, parent); 
        if (nm != null) {
            // add a named keymap, a class of bindings
            getKeymapTable().put(nm, map);
        }
        return map;
    }

    /**
     * Removes a named keymap previously added to the document.  Keymaps
     * with <code>null</code> names may not be removed in this way.
     *
     * @param nm  the name of the keymap to remove
     * @return the keymap that was removed
     */
    public static Keymap removeKeymap(String nm) {
        return getKeymapTable().remove(nm);
    }

    /**
     * Fetches a named keymap previously added to the document.
     * This does not work with <code>null</code>-named keymaps.
     *
     * @param nm  the name of the keymap
     * @return the keymap
     */
    public static Keymap getKeymap(String nm) {
        return getKeymapTable().get(nm);
    }

    private static HashMap<String,Keymap> getKeymapTable() {
        synchronized (KEYMAP_TABLE) {
            AppContext appContext = AppContext.getAppContext();
            HashMap<String,Keymap> keymapTable = 
                (HashMap<String,Keymap>)appContext.get(KEYMAP_TABLE);
            if (keymapTable == null) {
                keymapTable = new HashMap<String,Keymap>(17);
                appContext.put(KEYMAP_TABLE, keymapTable);
                //initialize default keymap
                Keymap binding = addKeymap(DEFAULT_KEYMAP, null);
                binding.setDefaultAction(new 
                                         DefaultEditorKit.DefaultKeyTypedAction());
            }
            return keymapTable;
        }
    }

    /**
     * Binding record for creating key bindings.
     * <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<sup><font size="-2">TM</font></sup>
     * has been added to the <code>java.beans</code> package.
     * Please see {@link java.beans.XMLEncoder}.
     */
    public static class KeyBinding {
        
        /**
         * The key.
         */
        public KeyStroke key;

        /**
         * The name of the action for the key.
         */
        public String actionName;

        /**
         * Creates a new key binding.
         *
         * @param key the key
         * @param actionName the name of the action for the key
         */
        public KeyBinding(KeyStroke key, String actionName) {
            this.key = key;
            this.actionName = actionName;
        }
    }

    /**
     * <p>
     * Loads a keymap with a bunch of 
     * bindings.  This can be used to take a static table of
     * definitions and load them into some keymap.  The following
     * example illustrates an example of binding some keys to
     * the cut, copy, and paste actions associated with a 
     * JTextComponent.  A code fragment to accomplish
     * this might look as follows:
     * <pre><code>
     *
     *   static final JTextComponent.KeyBinding[] defaultBindings = {
     *     new JTextComponent.KeyBinding(
     *       KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_MASK),
     *       DefaultEditorKit.copyAction),
     *     new JTextComponent.KeyBinding(
     *       KeyStroke.getKeyStroke(KeyEvent.VK_V, InputEvent.CTRL_MASK),
     *       DefaultEditorKit.pasteAction),
     *     new JTextComponent.KeyBinding(
     *       KeyStroke.getKeyStroke(KeyEvent.VK_X, InputEvent.CTRL_MASK),
     *       DefaultEditorKit.cutAction),
     *   };
     *
     *   JTextComponent c = new JTextPane();
     *   Keymap k = c.getKeymap();
     *   JTextComponent.loadKeymap(k, defaultBindings, c.getActions());
     * 
     * </code></pre>
     * The sets of bindings and actions may be empty but must be
     * non-<code>null</code>.
     *
     * @param map the keymap
     * @param bindings the bindings
     * @param actions the set of actions
     */
    public static void loadKeymap(Keymap map, KeyBinding[] bindings, Action[] actions) {
        Hashtable h = new Hashtable();
        for (int i = 0; i < actions.length; i++) {
            Action a = actions[i];
            String value = (String)a.getValue(Action.NAME);
            h.put((value!=null ? value:""), a);
        }
        for (int i = 0; i < bindings.length; i++) {
            Action a = (Action) h.get(bindings[i].actionName);
            if (a != null) {
                map.addActionForKeyStroke(bindings[i].key, a);
            }
        }
    }

    /**
     * Returns true if <code>klass</code> is NOT a JTextComponent and it or
     * one of its superclasses (stoping at JTextComponent) overrides
     * <code>processInputMethodEvent</code>. It is assumed this will be
     * invoked from within a <code>doPrivileged</code>, and it is also
     * assumed <code>klass</code> extends <code>JTextComponent</code>.
     */
    private static Boolean isProcessInputMethodEventOverridden(Class klass) {
        if (klass == JTextComponent.class) {
            return Boolean.FALSE;
        }
        Boolean retValue = (Boolean)overrideMap.get(klass.getName());

        if (retValue != null) {
            return retValue;
        }
        Boolean sOverriden = isProcessInputMethodEventOverridden(
                                       klass.getSuperclass());

        if (sOverriden.booleanValue()) {
            // If our superclass has overriden it, then by definition klass
            // overrides it.
            overrideMap.put(klass.getName(), sOverriden);
            return sOverriden;
        }
        // klass's superclass didn't override it, check for an override in
        // klass.
        try {
            Class[] classes = new Class[1];
            classes[0] = InputMethodEvent.class;

            Method m = klass.getDeclaredMethod("processInputMethodEvent",
                                               classes);
            retValue = Boolean.TRUE;
        } catch (NoSuchMethodException nsme) {
            retValue = Boolean.FALSE;
        }
        overrideMap.put(klass.getName(), retValue);
        return retValue;
    }
    
    /**
     * Fetches the current color used to render the 
     * caret.
     *
     * @return the color
     */
    public Color getCaretColor() {
        return caretColor;
    }

    /**
     * Sets the current color used to render the caret.
     * Setting to <code>null</code> effectively restores the default color.
     * Setting the color results in a PropertyChange event ("caretColor")
     * being fired.
     *
     * @param c the color
     * @see #getCaretColor
     * @beaninfo
     *  description: the color used to render the caret
     *        bound: true
     *    preferred: true
     */
    public void setCaretColor(Color c) {
        Color old = caretColor;
        caretColor = c;
        firePropertyChange("caretColor", old, caretColor);
    }

    /**
     * Fetches the current color used to render the 
     * selection.
     *
     * @return the color
     */
    public Color getSelectionColor() {
        return selectionColor;
    }

    /**
     * Sets the current color used to render the selection.
     * Setting the color to <code>null</code> is the same as setting
     * <code>Color.white</code>.  Setting the color results in a
     * PropertyChange event ("selectionColor").
     *
     * @param c the color
     * @see #getSelectionColor
     * @beaninfo
     *  description: color used to render selection background
     *        bound: true
     *    preferred: true
     */
    public void setSelectionColor(Color c) {
        Color old = selectionColor;
        selectionColor = c;
        firePropertyChange("selectionColor", old, selectionColor);
    }

    /**
     * Fetches the current color used to render the 
     * selected text.
     *
     * @return the color
     */
    public Color getSelectedTextColor() {
        return selectedTextColor;
    }

    /**
     * Sets the current color used to render the selected text.
     * Setting the color to <code>null</code> is the same as 
     * <code>Color.black</code>. Setting the color results in a
     * PropertyChange event ("selectedTextColor") being fired.
     *
     * @param c the color
     * @see #getSelectedTextColor
     * @beaninfo
     *  description: color used to render selected text
     *        bound: true
     *    preferred: true
     */
    public void setSelectedTextColor(Color c) {
        Color old = selectedTextColor;
        selectedTextColor = c;
        firePropertyChange("selectedTextColor", old, selectedTextColor);
    }

    /**
     * Fetches the current color used to render the 
     * disabled text.
     *
     * @return the color
     */
    public Color getDisabledTextColor() {
        return disabledTextColor;
    }

    /**
     * Sets the current color used to render the
     * disabled text.  Setting the color fires off a
     * PropertyChange event ("disabledTextColor").
     *
     * @param c the color
     * @see #getDisabledTextColor
     * @beaninfo
     *  description: color used to render disabled text
     *        bound: true
     *    preferred: true
     */
    public void setDisabledTextColor(Color c) {
        Color old = disabledTextColor;
        disabledTextColor = c;
        firePropertyChange("disabledTextColor", old, disabledTextColor);
    }

    /**
     * Replaces the currently selected content with new content
     * represented by the given string.  If there is no selection
     * this amounts to an insert of the given text.  If there
     * is no replacement text this amounts to a removal of the
     * current selection.  
     * <p>
     * This is the method that is used by the default implementation
     * of the action for inserting content that gets bound to the
     * keymap actions.
     * <p>
     * This method is thread safe, although most Swing methods
     * are not. Please see 
     * <A HREF="http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html">How
     * to Use Threads</A> for more information.     
     *
     * @param content  the content to replace the selection with
     */
    public void replaceSelection(String content) {
        Document doc = getDocument();
        if (doc != null) {
            try {
		boolean composedTextSaved = saveComposedText(caret.getDot());
                int p0 = Math.min(caret.getDot(), caret.getMark());
                int p1 = Math.max(caret.getDot(), caret.getMark());
                if (doc instanceof AbstractDocument) {
                    ((AbstractDocument)doc).replace(p0, p1 - p0, content,null);
                }
                else {
                    if (p0 != p1) {
                        doc.remove(p0, p1 - p0);
                    }
                    if (content != null && content.length() > 0) {
                        doc.insertString(p0, content, null);
                    }
                }
		if (composedTextSaved) {
		    restoreComposedText();
		}
            } catch (BadLocationException e) {
		UIManager.getLookAndFeel().provideErrorFeedback(JTextComponent.this);
            }
        }
    }

    /**
     * Fetches a portion of the text represented by the
     * component.  Returns an empty string if length is 0.
     *
     * @param offs the offset >= 0
     * @param len the length >= 0
     * @return the text
     * @exception BadLocationException if the offset or length are invalid
     */
    public String getText(int offs, int len) throws BadLocationException {
        return getDocument().getText(offs, len);
    }

    /**
     * Converts the given location in the model to a place in
     * the view coordinate system.
     * The component must have a positive size for 
     * this translation to be computed (i.e. layout cannot
     * be computed until the component has been sized).  The
     * component does not have to be visible or painted.
     *
     * @param pos the position >= 0
     * @return the coordinates as a rectangle, with (r.x, r.y) as the location
     *   in the coordinate system, or null if the component does
     *   not yet have a positive size.
     * @exception BadLocationException if the given position does not 
     *   represent a valid location in the associated document
     * @see TextUI#modelToView
     */
    public Rectangle modelToView(int pos) throws BadLocationException {
        return getUI().modelToView(this, pos);
    }

    /**
     * Converts the given place in the view coordinate system
     * to the nearest representative location in the model.
     * The component must have a positive size for 
     * this translation to be computed (i.e. layout cannot
     * be computed until the component has been sized).  The
     * component does not have to be visible or painted.
     *
     * @param pt the location in the view to translate
     * @return the offset >= 0 from the start of the document, 
     *   or -1 if the component does not yet have a positive
     *   size.
     * @see TextUI#viewToModel
     */
    public int viewToModel(Point pt) {
        return getUI().viewToModel(this, pt);
    }

    /**
     * Transfers the currently selected range in the associated
     * text model to the system clipboard, removing the contents
     * from the model.  The current selection is reset.  Does nothing
     * for <code>null</code> selections.
     *
     * @see java.awt.Toolkit#getSystemClipboard
     * @see java.awt.datatransfer.Clipboard
     */
    public void cut() {
	if (isEditable() && isEnabled()) {
            invokeAction("cut", TransferHandler.getCutAction());
	}
    }

    /**
     * Transfers the currently selected range in the associated
     * text model to the system clipboard, leaving the contents
     * in the text model.  The current selection remains intact.
     * Does nothing for <code>null</code> selections.
     *
     * @see java.awt.Toolkit#getSystemClipboard
     * @see java.awt.datatransfer.Clipboard
     */
    public void copy() {
        invokeAction("copy", TransferHandler.getCopyAction());
    }
    
    /**
     * Transfers the contents of the system clipboard into the
     * associated text model.  If there is a selection in the
     * associated view, it is replaced with the contents of the
     * clipboard.  If there is no selection, the clipboard contents
     * are inserted in front of the current insert position in 
     * the associated view.  If the clipboard is empty, does nothing.
     *
     * @see #replaceSelection
     * @see java.awt.Toolkit#getSystemClipboard
     * @see java.awt.datatransfer.Clipboard
     */ 
    public void paste() {
	if (isEditable() && isEnabled()) {
            invokeAction("paste", TransferHandler.getPasteAction());
	}
    }

    /**
     * This is a conveniance method that is only useful for
     * <code>cut</code>, <code>copy</code> and <code>paste</code>.  If
     * an <code>Action</code> with the name <code>name</code> does not
     * exist in the <code>ActionMap</code>, this will attemp to install a
     * <code>TransferHandler</code> and then use <code>altAction</code>.
     */
    private void invokeAction(String name, Action altAction) {
        ActionMap map = getActionMap();
        Action action = null;

        if (map != null) {
            action = map.get(name);
        }
        if (action == null) {
            installDefaultTransferHandlerIfNecessary();
            action = altAction;
        }
        action.actionPerformed(new ActionEvent(this,
                               ActionEvent.ACTION_PERFORMED, (String)action.
                               getValue(Action.NAME),
                               EventQueue.getMostRecentEventTime(),
                               getCurrentEventModifiers()));
    }

    /**
     * If the current <code>TransferHandler</code> is null, this will
     * install a new one.
     */
    private void installDefaultTransferHandlerIfNecessary() {
        if (getTransferHandler() == null) {
            if (defaultTransferHandler == null) {
                defaultTransferHandler = new DefaultTransferHandler();
            }
            setTransferHandler(defaultTransferHandler);
        }
    }

    /**
     * Moves the caret to a new position, leaving behind a mark
     * defined by the last time <code>setCaretPosition</code> was
     * called.  This forms a selection.
     * If the document is <code>null</code>, does nothing. The position
     * must be between 0 and the length of the component's text or else
     * an exception is thrown.
     *
     * @param pos the position
     * @exception    IllegalArgumentException if the value supplied
     *               for <code>position</code> is less than zero or greater
     *               than the component's text length
     * @see #setCaretPosition
     */
    public void moveCaretPosition(int pos) {
        Document doc = getDocument();
        if (doc != null) {
            if (pos > doc.getLength() || pos < 0) {
                throw new IllegalArgumentException("bad position: " + pos);
            }
            caret.moveDot(pos);
        }
    }

    /**
     * The bound property name for the focus accelerator.
     */ 
    public static final String FOCUS_ACCELERATOR_KEY = "focusAcceleratorKey";

    /**
     * Sets the key accelerator that will cause the receiving text
     * component to get the focus.  The accelerator will be the 
     * key combination of the <em>alt</em> key and the character
     * given (converted to upper case).  By default, there is no focus
     * accelerator key.  Any previous key accelerator setting will be
     * superseded.  A '\0' key setting will be registered, and has the
     * effect of turning off the focus accelerator.  When the new key
     * is set, a PropertyChange event (FOCUS_ACCELERATOR_KEY) will be fired.
     *
     * @param aKey the key
     * @see #getFocusAccelerator
     * @beaninfo
     *  description: accelerator character used to grab focus
     *        bound: true
     */
    public void setFocusAccelerator(char aKey) {
        aKey = Character.toUpperCase(aKey);
        char old = focusAccelerator;
        focusAccelerator = aKey;
        // Fix for 4341002: value of FOCUS_ACCELERATOR_KEY is wrong.
        // So we fire both FOCUS_ACCELERATOR_KEY, for compatibility,
        // and the correct event here.
        firePropertyChange(FOCUS_ACCELERATOR_KEY, old, focusAccelerator);
        firePropertyChange("focusAccelerator", old, focusAccelerator);
    }

    /**
     * Returns the key accelerator that will cause the receiving
     * text component to get the focus.  Return '\0' if no focus
     * accelerator has been set.
     *
     * @return the key
     */
    public char getFocusAccelerator() {
        return focusAccelerator;
    }

    /**
     * Initializes from a stream.  This creates a
     * model of the type appropriate for the component
     * and initializes the model from the stream.
     * By default this will load the model as plain
     * text.  Previous contents of the model are discarded.
     *
     * @param in the stream to read from
     * @param desc an object describing the stream; this
     *   might be a string, a File, a URL, etc.  Some kinds
     *   of documents (such as html for example) might be
     *   able to make use of this information; if non-<code>null</code>,
     *   it is added as a property of the document
     * @exception IOException as thrown by the stream being
     *  used to initialize
     * @see EditorKit#createDefaultDocument
     * @see #setDocument
     * @see PlainDocument
     */
    public void read(Reader in, Object desc) throws IOException {
        EditorKit kit = getUI().getEditorKit(this);
        Document doc = kit.createDefaultDocument();
        if (desc != null) {
            doc.putProperty(Document.StreamDescriptionProperty, desc);
        }
        try {
            kit.read(in, doc, 0);
            setDocument(doc);
        } catch (BadLocationException e) {
            throw new IOException(e.getMessage());
        }
    }

    /**
     * Stores the contents of the model into the given
     * stream.  By default this will store the model as plain
     * text.
     *
     * @param out the output stream
     * @exception IOException on any I/O error
     */
    public void write(Writer out) throws IOException {
        Document doc = getDocument();
        try {
            getUI().getEditorKit(this).write(out, doc, 0, doc.getLength());
        } catch (BadLocationException e) {
            throw new IOException(e.getMessage());
        }
    }

    public void removeNotify() {
        super.removeNotify();
        if (getFocusedComponent() == this) {
            AppContext.getAppContext().remove(FOCUSED_COMPONENT);
        }
    }

    // --- java.awt.TextComponent methods ------------------------

    /**
     * Sets the position of the text insertion caret for the 
     * <code>TextComponent</code>.  Note that the caret tracks change,
     * so this may move if the underlying text of the component is changed.
     * If the document is <code>null</code>, does nothing. The position
     * must be between 0 and the length of the component's text or else
     * an exception is thrown.
     *
     * @param position the position
     * @exception    IllegalArgumentException if the value supplied
     *               for <code>position</code> is less than zero or greater
     *               than the component's text length
     * @beaninfo
     * description: the caret position
     */
    public void setCaretPosition(int position) {
        Document doc = getDocument();
        if (doc != null) {
	    if (position > doc.getLength() || position < 0) {
		throw new IllegalArgumentException("bad position: " + position);
	    }
            caret.setDot(position);
        }
    }

    /**
     * Returns the position of the text insertion caret for the 
     * text component.
     *
     * @return the position of the text insertion caret for the
     *  text component >= 0
     */
    public int getCaretPosition() {
        return caret.getDot();
    }

    /**
     * Sets the text of this <code>TextComponent</code>
     * to the specified text.  If the text is <code>null</code>
     * or empty, has the effect of simply deleting the old text.
     * When text has been inserted, the resulting caret location
     * is determined by the implementation of the caret class.
     * <p>
     * This method is thread safe, although most Swing methods
     * are not. Please see 
     * <A HREF="http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html">How
     * to Use Threads</A> for more information.     
     *
     * Note that text is not a bound property, so no <code>PropertyChangeEvent
     * </code> is fired when it changes. To listen for changes to the text,
     * use <code>DocumentListener</code>.
     *
     * @param t the new text to be set
     * @see #getText
     * @see DefaultCaret
     * @beaninfo
     * description: the text of this component
     */
    public void setText(String t) {
        try {
            Document doc = getDocument();
            if (doc instanceof AbstractDocument) {
                ((AbstractDocument)doc).replace(0, doc.getLength(), t,null);
            }
            else {
                doc.remove(0, doc.getLength());
                doc.insertString(0, t, null);
            }
        } catch (BadLocationException e) {
	    UIManager.getLookAndFeel().provideErrorFeedback(JTextComponent.this);
        }
    }

    /**
     * Returns the text contained in this <code>TextComponent</code>.
     * If the underlying document is <code>null</code>,
     * will give a <code>NullPointerException</code>.
     *
     * Note that text is not a bound property, so no <code>PropertyChangeEvent
     * </code> is fired when it changes. To listen for changes to the text,
     * use <code>DocumentListener</code>.
     *
     * @return the text
     * @exception NullPointerException if the document is <code>null</code>
     * @see #setText
     */
    public String getText() {
        Document doc = getDocument();
        String txt;
        try {
            txt = doc.getText(0, doc.getLength());
        } catch (BadLocationException e) {
            txt = null;
        }
        return txt;
    }

    /**
     * Returns the selected text contained in this
     * <code>TextComponent</code>.  If the selection is 
     * <code>null</code> or the document empty, returns <code>null</code>.
     *
     * @return the text
     * @exception IllegalArgumentException if the selection doesn't
     *  have a valid mapping into the document for some reason
     * @see #setText
     */
    public String getSelectedText() {
        String txt = null;
        int p0 = Math.min(caret.getDot(), caret.getMark());
        int p1 = Math.max(caret.getDot(), caret.getMark());
        if (p0 != p1) {
            try {
                Document doc = getDocument();
                txt = doc.getText(p0, p1 - p0);
            } catch (BadLocationException e) {
		throw new IllegalArgumentException(e.getMessage());
            }
        }
        return txt;
    }

    /**
     * Returns the boolean indicating whether this 
     * <code>TextComponent</code> is editable or not.
     *
     * @return the boolean value
     * @see #setEditable
     */
    public boolean isEditable() {
        return editable;
    }

    /**
     * Sets the specified boolean to indicate whether or not this
     * <code>TextComponent</code> should be editable.
     * A PropertyChange event ("editable") is fired when the
     * state is changed.
     *
     * @param b the boolean to be set
     * @see #isEditable
     * @beaninfo
     * description: specifies if the text can be edited
     *       bound: true
     */
    public void setEditable(boolean b) {
	if (b != editable) {
	    boolean oldVal = editable;
	    editable = b;
	    enableInputMethods(editable);
	    firePropertyChange("editable", Boolean.valueOf(oldVal), Boolean.valueOf(editable));
	    repaint();
	}
    }

    /**
     * Returns the selected text's start position.  Return 0 for an
     * empty document, or the value of dot if no selection.
     *
     * @return the start position >= 0
     */
    public int getSelectionStart() {
        int start = Math.min(caret.getDot(), caret.getMark());
        return start;
    }

    /**
     * Sets the selection start to the specified position.  The new
     * starting point is constrained to be before or at the current
     * selection end.
     * <p>
     * This is available for backward compatibility to code 
     * that called this method on <code>java.awt.TextComponent</code>.
     * This is implemented to forward to the <code>Caret</code>
     * implementation which is where the actual selection is maintained.
     *
     * @param selectionStart the start position of the text >= 0
     * @beaninfo
     * description: starting location of the selection.
     */
    public void setSelectionStart(int selectionStart) {
        /* Route through select method to enforce consistent policy
         * between selectionStart and selectionEnd.
         */
        select(selectionStart, getSelectionEnd());
    }

    /**
     * Returns the selected text's end position.  Return 0 if the document
     * is empty, or the value of dot if there is no selection.
     *
     * @return the end position >= 0
     */
    public int getSelectionEnd() {
        int end = Math.max(caret.getDot(), caret.getMark());
        return end;
    }

    /**
     * Sets the selection end to the specified position.  The new
     * end point is constrained to be at or after the current
     * selection start.
     * <p>
     * This is available for backward compatibility to code 
     * that called this method on <code>java.awt.TextComponent</code>.
     * This is implemented to forward to the <code>Caret</code>
     * implementation which is where the actual selection is maintained.
     *
     * @param selectionEnd the end position of the text >= 0
     * @beaninfo
     * description: ending location of the selection.
     */
    public void setSelectionEnd(int selectionEnd) {
        /* Route through select method to enforce consistent policy
         * between selectionStart and selectionEnd.
         */
        select(getSelectionStart(), selectionEnd);
    }
    
    /**
     * Selects the text between the specified start and end positions.
     * <p>
     * This method sets the start and end positions of the 
     * selected text, enforcing the restriction that the start position 
     * must be greater than or equal to zero.  The end position must be 
     * greater than or equal to the start position, and less than or 
     * equal to the length of the text component's text.
     * <p>
     * If the caller supplies values that are inconsistent or out of 
     * bounds, the method enforces these constraints silently, and 
     * without failure. Specifically, if the start position or end 
     * position is greater than the length of the text, it is reset to 
     * equal the text length. If the start position is less than zero, 
     * it is reset to zero, and if the end position is less than the 
     * start position, it is reset to the start position.
     * <p>
     * This call is provided for backward compatibility.
     * It is routed to a call to <code>setCaretPosition</code>
     * followed by a call to <code>moveCaretPosition</code>.
     * The preferred way to manage selection is by calling
     * those methods directly.
     *
     * @param selectionStart the start position of the text
     * @param selectionEnd the end position of the text
     * @see #setCaretPosition
     * @see #moveCaretPosition
     */
    public void select(int selectionStart, int selectionEnd) {
	// argument adjustment done by java.awt.TextComponent
        int docLength = getDocument().getLength();
        
	if (selectionStart < 0) {
	    selectionStart = 0;
	}
        if (selectionStart > docLength) {
            selectionStart = docLength;
        }
        if (selectionEnd > docLength) {
            selectionEnd = docLength;
	}
	if (selectionEnd < selectionStart) {
	    selectionEnd = selectionStart;
	}

        setCaretPosition(selectionStart);
        moveCaretPosition(selectionEnd);
    }

    /**
     * Selects all the text in the <code>TextComponent</code>.
     * Does nothing on a <code>null</code> or empty document.
     */
    public void selectAll() {
        Document doc = getDocument();
        if (doc != null) {
            setCaretPosition(0);
            moveCaretPosition(doc.getLength());
        }
    }

    // --- Tooltip Methods ---------------------------------------------

    /**
     * Returns the string to be used as the tooltip for <code>event</code>.
     * This will return one of:
     * <ol>
     *  <li>If <code>setToolTipText</code> has been invoked with a 
     *      non-<code>null</code>
     *      value, it will be returned, otherwise
     *  <li>The value from invoking <code>getToolTipText</code> on
     *      the UI will be returned.
     * </ol>
     * By default <code>JTextComponent</code> does not register
     * itself with the <code>ToolTipManager</code>.
     * This means that tooltips will NOT be shown from the
     * <code>TextUI</code> unless <code>registerComponent</code> has
     * been invoked on the <code>ToolTipManager</code>.
     *
     * @param event the event in question
     * @return the string to be used as the tooltip for <code>event</code>
     * @see javax.swing.JComponent#setToolTipText
     * @see javax.swing.plaf.TextUI#getToolTipText
     * @see javax.swing.ToolTipManager#registerComponent
     */
    public String getToolTipText(MouseEvent event) {
        String retValue = super.getToolTipText(event);

        if (retValue == null) {
            TextUI ui = getUI();
            if (ui != null) {
                retValue = ui.getToolTipText(this, new Point(event.getX(),
                                                             event.getY()));
            }
        }
        return retValue;
    }

    // --- Scrollable methods ---------------------------------------------

    /**
     * Returns the preferred size of the viewport for a view component.
     * This is implemented to do the default behavior of returning
     * the preferred size of the component.
     * 
     * @return the <code>preferredSize</code> of a <code>JViewport</code>
     * whose view is this <code>Scrollable</code>
     */
    public Dimension getPreferredScrollableViewportSize() {
        return getPreferredSize();
    }


    /**
     * Components that display logical rows or columns should compute
     * the scroll increment that will completely expose one new row
     * or column, depending on the value of orientation.  Ideally, 
     * components should handle a partially exposed row or column by 
     * returning the distance required to completely expose the item.
     * <p>
     * The default implementation of this is to simply return 10% of
     * the visible area.  Subclasses are likely to be able to provide
     * a much more reasonable value.
     * 
     * @param visibleRect the view area visible within the viewport
     * @param orientation either <code>SwingConstants.VERTICAL</code> or
     *   <code>SwingConstants.HORIZONTAL</code>
     * @param direction less than zero to scroll up/left, greater than
     *   zero for down/right
     * @return the "unit" increment for scrolling in the specified direction
     * @exception IllegalArgumentException for an invalid orientation
     * @see JScrollBar#setUnitIncrement
     */
    public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
        switch(orientation) {
        case SwingConstants.VERTICAL:
            return visibleRect.height / 10;
        case SwingConstants.HORIZONTAL:
            return visibleRect.width / 10;
        default:
            throw new IllegalArgumentException("Invalid orientation: " + orientation);
        }
    }


    /**
     * Components that display logical rows or columns should compute
     * the scroll increment that will completely expose one block
     * of rows or columns, depending on the value of orientation. 
     * <p>
     * The default implementation of this is to simply return the visible
     * area.  Subclasses will likely be able to provide a much more 
     * reasonable value.
     * 
     * @param visibleRect the view area visible within the viewport
     * @param orientation either <code>SwingConstants.VERTICAL</code> or
     *   <code>SwingConstants.HORIZONTAL</code>
     * @param direction less than zero to scroll up/left, greater than zero
     *  for down/right
     * @return the "block" increment for scrolling in the specified direction
     * @exception IllegalArgumentException for an invalid orientation
     * @see JScrollBar#setBlockIncrement
     */
    public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
        switch(orientation) {
        case SwingConstants.VERTICAL:
            return visibleRect.height;
        case SwingConstants.HORIZONTAL:
            return visibleRect.width;
        default:
            throw new IllegalArgumentException("Invalid orientation: " + orientation);
        }
    }  
    

    /**
     * Returns true if a viewport should always force the width of this 
     * <code>Scrollable</code> to match the width of the viewport.
     * For example a normal text view that supported line wrapping
     * would return true here, since it would be undesirable for
     * wrapped lines to disappear beyond the right
     * edge of the viewport.  Note that returning true for a
     * <code>Scrollable</code> whose ancestor is a <code>JScrollPane</code>
     * effectively disables horizontal scrolling.
     * <p>
     * Scrolling containers, like <code>JViewport</code>,
     * will use this method each time they are validated.  
     * 
     * @return true if a viewport should force the <code>Scrollable</code>s
     *   width to match its own
     */
    public boolean getScrollableTracksViewportWidth() {
	if (getParent() instanceof JViewport) {
	    return (((JViewport)getParent()).getWidth() > getPreferredSize().width);
	}
	return false;
    }

    /**
     * Returns true if a viewport should always force the height of this 
     * <code>Scrollable</code> to match the height of the viewport.
     * For example a columnar text view that flowed text in left to
     * right columns could effectively disable vertical scrolling by 
     * returning true here.
     * <p>
     * Scrolling containers, like <code>JViewport</code>,
     * will use this method each time they are validated.  
     * 
     * @return true if a viewport should force the Scrollables height
     *   to match its own
     */
    public boolean getScrollableTracksViewportHeight() {
	if (getParent() instanceof JViewport) {
	    return (((JViewport)getParent()).getHeight() > getPreferredSize().height);
	}
	return false;
    }


//////////////////
// Printing Support
//////////////////

    /**
     * A convenience print method that displays a print dialog, and then
     * prints this {@code JTextComponent} in <i>interactive</i> mode with no
     * header or footer text. Note: this method
     * blocks until printing is done.
     * <p>
     * Note: In <i>headless</i> mode, no dialogs will be shown.
     * 
     * <p> This method calls the full featured 
     * {@link #print(MessageFormat, MessageFormat, boolean, PrintService, PrintRequestAttributeSet, boolean)
     * print} method to perform printing.
     * @return {@code true}, unless printing is canceled by the user
     * @throws PrinterException if an error in the print system causes the job
     *         to be aborted
     * @throws SecurityException if this thread is not allowed to
     *                           initiate a print job request
     *         
     * @see #print(MessageFormat, MessageFormat, boolean, PrintService, PrintRequestAttributeSet, boolean)
     * 
     * @since 1.6
     */
    
    public boolean print() throws PrinterException {
        return print(null, null, true, null, null, true);
    }
    
    /**
     * A convenience print method that displays a print dialog, and then
     * prints this {@code JTextComponent} in <i>interactive</i> mode with 
     * the specified header and footer text. Note: this method
     * blocks until printing is done.
     * <p>
     * Note: In <i>headless</i> mode, no dialogs will be shown.
     * 
     * <p> This method calls the full featured 
     * {@link #print(MessageFormat, MessageFormat, boolean, PrintService, PrintRequestAttributeSet, boolean)
     * print} method to perform printing.
     * @param headerFormat the text, in {@code MessageFormat}, to be
     *        used as the header, or {@code null} for no header
     * @param footerFormat the text, in {@code MessageFormat}, to be
     *        used as the footer, or {@code null} for no footer
     * @return {@code true}, unless printing is canceled by the user
     * @throws PrinterException if an error in the print system causes the job
     *         to be aborted
     * @throws SecurityException if this thread is not allowed to
     *                           initiate a print job request
     *         
     * @see #print(MessageFormat, MessageFormat, boolean, PrintService, PrintRequestAttributeSet, boolean)
     * @see java.text.MessageFormat     
     * @since 1.6
     */
    public boolean print(final MessageFormat headerFormat,
            final MessageFormat footerFormat) throws PrinterException {
        return print(headerFormat, footerFormat, true, null, null, true);
    }
    
    /**
     * Prints the content of this {@code JTextComponent}. Note: this method
     * blocks until printing is done.
     * 
     * <p>
     * Page header and footer text can be added to the output by providing
     * {@code MessageFormat} arguments. The printing code requests
     * {@code Strings} from the formats, providing a single item which may be
     * included in the formatted string: an {@code Integer} representing the
     * current page number.
     * 
     * <p>
     * {@code showPrintDialog boolean} parameter allows you to specify whether
     * a print dialog is displayed to the user. When it is, the user
     * may use the dialog to change printing attributes or even cancel the
     * print. 
     *
     * <p> 
     * {@code service} allows you to provide the initial 
     * {@code PrintService} for the print dialog, or to specify 
     * {@code PrintService} to print to when the dialog is not shown.
     *
     * <p> 
     * {@code attributes} can be used to provide the
     * initial values for the print dialog, or to supply any needed
     * attributes when the dialog is not shown. {@code attributes} can
     * be used to control how the job will print, for example
     * <i>duplex</i> or <i>single-sided</i>.
     *
     * <p> 
     * {@code interactive boolean} parameter allows you to specify
     * whether to perform printing in <i>interactive</i>
     * mode. If {@code true}, a progress dialog, with an abort option,
     * is displayed for the duration of printing.  This dialog is
     * <i>modal</i> when {@code print} is invoked on the <i>Event Dispatch
     * Thread</i> and <i>non-modal</i> otherwise. <b>Warning</b>:
     * calling this method on the <i>Event Dispatch Thread</i> with {@code
     * interactive false} blocks <i>all</i> events, including repaints, from
     * being processed until printing is complete. It is only
     * recommended when printing from an application with no
     * visible GUI.
     *
     * <p> 
     * Note: In <i>headless</i> mode, {@code showPrintDialog} and
     * {@code interactive} parameters are ignored and no dialogs are
     * shown.
     *
     * <p>
     * This method ensures the {@code document} is not mutated during printing.
     * To indicate it visually, {@code setEnabled(false)} is set for the
     * duration of printing.
     * 
     * <p>
     * This method uses {@link #getPrintable} to render document content.
     * 
     * <p>
     * This method is thread-safe, although most Swing methods are not. Please
     * see <A
     * HREF="http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html">
     * How to Use Threads</A> for more information.
     * 
     * <p>
     * <b>Sample Usage</b>. This code snippet shows a cross-platform print
     * dialog and then prints the {@code JTextComponent} in <i>interactive</i> mode
     * unless the user cancels the dialog:
     * 
     * <pre>
     * textComponent.print(new MessageFormat(&quot;My text component header&quot;),
     *     new MessageFormat(&quot;Footer. Page - {0}&quot;), true, null, null, true);
     * </pre>
     * <p>
     * Executing this code off the <i>Event Dispatch Thread</i> 
     * performs printing on the <i>background</i>. 
     * The following pattern might be used for <i>background</i> 
     * printing:
     * <pre>
     *     FutureTask&lt;Boolean&gt; future =
     *         new FutureTask&lt;Boolean&gt;(
     *             new Callable&lt;Boolean&gt;() {
     *                 public Boolean call() {
     *                     return textComponent.print(.....);
     *                 }  
     *             });
     *     executor.execute(future);
     * </pre> 
     * 
     * @param headerFormat the text, in {@code MessageFormat}, to be
     *        used as the header, or {@code null} for no header
     * @param footerFormat the text, in {@code MessageFormat}, to be
     *        used as the footer, or {@code null} for no footer
     * @param showPrintDialog {@code true} to display a print dialog,
     *        {@code false} otherwise
     * @param service initial {@code PrintService}, or {@code null} for the
     *        default
     * @param attributes the job attributes to be applied to the print job, or
     *        {@code null} for none
     * @param interactive whether to print in an interactive mode
     * @return {@code true}, unless printing is canceled by the user
     * @throws PrinterException if an error in the print system causes the job
     *         to be aborted
     * @throws SecurityException if this thread is not allowed to
     *                           initiate a print job request
     * 
     * @see #getPrintable
     * @see java.text.MessageFormat
     * @see java.awt.GraphicsEnvironment#isHeadless
     * @see java.util.concurrent.FutureTask
     * 
     * @since 1.6
     */
    public boolean print(final MessageFormat headerFormat,
            final MessageFormat footerFormat, 
            final boolean showPrintDialog,
            final PrintService service,
            final PrintRequestAttributeSet attributes, 
            final boolean interactive)
            throws PrinterException {

        final PrinterJob job = PrinterJob.getPrinterJob();
        final Printable printable;
        final PrintingStatus printingStatus;
        final boolean isHeadless = GraphicsEnvironment.isHeadless();
        final boolean isEventDispatchThread = 
            SwingUtilities.isEventDispatchThread();
        final Printable textPrintable = getPrintable(headerFormat, footerFormat);
        if (interactive && ! isHeadless) {
            printingStatus = 
                PrintingStatus.createPrintingStatus(this, job);
            printable = 
                printingStatus.createNotificationPrintable(textPrintable);
        } else {
            printingStatus = null; 
            printable = textPrintable;
        }

        if (service != null) {
            job.setPrintService(service);
        }

        job.setPrintable(printable);

        final PrintRequestAttributeSet attr = (attributes == null) 
            ? new HashPrintRequestAttributeSet() 
            : attributes;        

        if (showPrintDialog && ! isHeadless && ! job.printDialog(attr)) {
            return false;
        }

        /*
         * there are three cases for printing:
         * 1. print non interactively (! interactive || isHeadless)
         * 2. print interactively off EDT
         * 3. print interactively on EDT
         * 
         * 1 and 2 prints on the current thread (3 prints on another thread)
         * 2 and 3 deal with PrintingStatusDialog
         */
        final Callable<Object> doPrint = 
            new Callable<Object>() {
                public Object call() throws Exception {
                    try {
                        job.print(attr);
                    } finally {
                        if (printingStatus != null) {
                            printingStatus.dispose();
                        }
                    }
                    return null;
                }
            };

        final FutureTask<Object> futurePrinting = 
            new FutureTask<Object>(doPrint);

        final Runnable runnablePrinting = 
            new Runnable() {
                public void run() {
                    //disable component
                    boolean wasEnabled = false;
                    if (isEventDispatchThread) {
                        if (isEnabled()) {
                            wasEnabled = true;
                            setEnabled(false);
                        }
                    } else {
                        try {
                            wasEnabled = SwingUtilities2.submit(
                                new Callable<Boolean>() {
                                    public Boolean call() throws Exception {
                                        boolean rv = isEnabled();
                                        if (rv) {
                                            setEnabled(false);
                                        } 
                                        return rv;
                                    }
                                }).get();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        } catch (ExecutionException e) {
                            Throwable cause = e.getCause();
                            if (cause instanceof Error) {
                                throw (Error) cause;
                            } 
                            if (cause instanceof RuntimeException) {
                                throw (RuntimeException) cause;
                            } 
                            throw new AssertionError(cause);
                        }
                    }

                    getDocument().render(futurePrinting);

                    //enable component
                    if (wasEnabled) {
                        if (isEventDispatchThread) {
                            setEnabled(true);
                        } else {
                            try {
                                SwingUtilities2.submit(
                                    new Runnable() {
                                        public void run() {
                                            setEnabled(true);
                                        }
                                    }, null).get();
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            } catch (ExecutionException e) {
                                Throwable cause = e.getCause();
                                if (cause instanceof Error) {
                                    throw (Error) cause;
                                } 
                                if (cause instanceof RuntimeException) {
                                    throw (RuntimeException) cause;
                                } 
                                throw new AssertionError(cause);
                            }
                        }
                    }
                }
            };
        
        if (! interactive || isHeadless) {
            runnablePrinting.run();
        } else {
            if (isEventDispatchThread) {
                (new Thread(runnablePrinting)).start();
                printingStatus.showModal(true);
            } else {
                printingStatus.showModal(false);
                runnablePrinting.run();
            }
        }
        
        //the printing is done successfully or otherwise. 
        //dialog is hidden if needed.
        try {
            futurePrinting.get();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            Throwable cause = e.getCause();
            if (cause instanceof PrinterAbortException) {
                if (printingStatus != null
                    && printingStatus.isAborted()) {
                    return false;
                } else {
                    throw (PrinterAbortException) cause;
                }
            } else if (cause instanceof PrinterException) {
                throw (PrinterException) cause;
            } else if (cause instanceof RuntimeException) {
                throw (RuntimeException) cause;
            } else if (cause instanceof Error) {
                throw (Error) cause;
            } else {
                throw new AssertionError(cause);
            }
        }
        return true;
    }
    

    /**
     * Returns a {@code Printable} to use for printing the content of this
     * {@code JTextComponent}. The returned {@code Printable} prints
     * the document as it looks on the screen except being reformatted
     * to fit the paper.
     * The returned {@code Printable} can be wrapped inside another
     * {@code Printable} in order to create complex reports and
     * documents.  
     *
     *
     * <p>
     * The returned {@code Printable} shares the {@code document} with this
     * {@code JTextComponent}. It is the responsibility of the developer to
     * ensure that the {@code document} is not mutated while this {@code Printable}
     * is used. Printing behavior is undefined when the {@code document} is
     * mutated during printing.
     * 
     * <p>
     * Page header and footer text can be added to the output by providing
     * {@code MessageFormat} arguments. The printing code requests
     * {@code Strings} from the formats, providing a single item which may be
     * included in the formatted string: an {@code Integer} representing the
     * current page number.
     *
     * <p> 
     * The returned {@code Printable} when printed, formats the
     * document content appropriately for the page size. For correct
     * line wrapping the {@code imageable width} of all pages must be the
     * same. See {@link java.awt.print.PageFormat#getImageableWidth}.
     *
     * <p>
     * This method is thread-safe, although most Swing methods are not. Please
     * see <A
     * HREF="http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html">
     * How to Use Threads</A> for more information.
     *
     * <p>
     * The returned {@code Printable} can be printed on any thread.
     *
     * <p>
     * This implementation returned {@code Printable} performs all painting on
     * the <i>Event Dispatch Thread</i>, regardless of what thread it is
     * used on.
     * 
     * @param headerFormat the text, in {@code MessageFormat}, to be
     *        used as the header, or {@code null} for no header
     * @param footerFormat the text, in {@code MessageFormat}, to be
     *        used as the footer, or {@code null} for no footer
     * @return a {@code Printable} for use in printing content of this
     *         {@code JTextComponent}
     * 
     * 
     * @see java.awt.print.Printable
     * @see java.awt.print.PageFormat
     * @see javax.swing.text.Document#render(java.lang.Runnable)
     *
     * @since 1.6
     */
    public Printable getPrintable(final MessageFormat headerFormat,
                                  final MessageFormat footerFormat) {
        return TextComponentPrintable.getPrintable(
                   this, headerFormat, footerFormat);
    }


/////////////////
// Accessibility support
////////////////


    /**
     * Gets the <code>AccessibleContext</code> associated with this
     * <code>JTextComponent</code>. For text components,
     * the <code>AccessibleContext</code> takes the form of an 
     * <code>AccessibleJTextComponent</code>. 
     * A new <code>AccessibleJTextComponent</code> instance
     * is created if necessary.
     *
     * @return an <code>AccessibleJTextComponent</code> that serves as the 
     *         <code>AccessibleContext</code> of this
     *	       <code>JTextComponent</code>
     */
    public AccessibleContext getAccessibleContext() {
        if (accessibleContext == null) {
            accessibleContext = new AccessibleJTextComponent();
        }
        return accessibleContext;
    }

    /**
     * This class implements accessibility support for the 
     * <code>JTextComponent</code> class.  It provides an implementation of 
     * the Java Accessibility API appropriate to menu user-interface elements.
     * <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<sup><font size="-2">TM</font></sup>
     * has been added to the <code>java.beans</code> package.
     * Please see {@link java.beans.XMLEncoder}.
     */
    public class AccessibleJTextComponent extends AccessibleJComponent 
    implements AccessibleText, CaretListener, DocumentListener,
               AccessibleAction, AccessibleEditableText,
               AccessibleExtendedText {

        int caretPos;
        Point oldLocationOnScreen;

        /**
         * Constructs an AccessibleJTextComponent.  Adds a listener to track
         * caret change.
         */
        public AccessibleJTextComponent() {
            Document doc = JTextComponent.this.getDocument();
            if (doc != null) {
                doc.addDocumentListener(this);
            }
            JTextComponent.this.addCaretListener(this);
            caretPos = getCaretPosition();

            try {
	        oldLocationOnScreen = getLocationOnScreen();
            } catch (IllegalComponentStateException iae) {
            }

	    // Fire a ACCESSIBLE_VISIBLE_DATA_PROPERTY PropertyChangeEvent
	    // when the text component moves (e.g., when scrolling).
	    // Using an anonymous class since making AccessibleJTextComponent
	    // implement ComponentListener would be an API change.
	    JTextComponent.this.addComponentListener(new ComponentAdapter() {

	        public void componentMoved(ComponentEvent e) {
                    try {
		        Point newLocationOnScreen = getLocationOnScreen();
		        firePropertyChange(ACCESSIBLE_VISIBLE_DATA_PROPERTY,
				           oldLocationOnScreen, 
				           newLocationOnScreen);
		    
		        oldLocationOnScreen = newLocationOnScreen;
                    } catch (IllegalComponentStateException iae) {
                    }
		}
	    });
        }

        /**
         * Handles caret updates (fire appropriate property change event,
         * which are AccessibleContext.ACCESSIBLE_CARET_PROPERTY and
         * AccessibleContext.ACCESSIBLE_SELECTION_PROPERTY).
         * This keeps track of the dot position internally.  When the caret
         * moves, the internal position is updated after firing the event.
         *
         * @param e the CaretEvent
         */
        public void caretUpdate(CaretEvent e) {
            int dot = e.getDot();
            int mark = e.getMark();
            if (caretPos != dot) {
                // the caret moved
                firePropertyChange(ACCESSIBLE_CARET_PROPERTY,
                    new Integer(caretPos), new Integer(dot));
                caretPos = dot;

                try {
                    oldLocationOnScreen = getLocationOnScreen();
                } catch (IllegalComponentStateException iae) {
                }
            }
            if (mark != dot) {
                // there is a selection
                firePropertyChange(ACCESSIBLE_SELECTION_PROPERTY, null, 
                    getSelectedText());
            }
        }

        // DocumentListener methods

        /**
         * Handles document insert (fire appropriate property change event
         * which is AccessibleContext.ACCESSIBLE_TEXT_PROPERTY).
         * This tracks the changed offset via the event.
         *
         * @param e the DocumentEvent
         */
        public void insertUpdate(DocumentEvent e) {
            final Integer pos = new Integer (e.getOffset());
            if (SwingUtilities.isEventDispatchThread()) {
                firePropertyChange(ACCESSIBLE_TEXT_PROPERTY, null, pos);
            } else {
                Runnable doFire = new Runnable() {
                    public void run() {
                        firePropertyChange(ACCESSIBLE_TEXT_PROPERTY, 
                                           null, pos);
                    }
                };
                SwingUtilities.invokeLater(doFire);
            }
        }

        /**
         * Handles document remove (fire appropriate property change event,
         * which is AccessibleContext.ACCESSIBLE_TEXT_PROPERTY).
         * This tracks the changed offset via the event.
         *
         * @param e the DocumentEvent
         */
        public void removeUpdate(DocumentEvent e) {
            final Integer pos = new Integer (e.getOffset());
            if (SwingUtilities.isEventDispatchThread()) {
                firePropertyChange(ACCESSIBLE_TEXT_PROPERTY, null, pos);
            } else {
                Runnable doFire = new Runnable() {
                    public void run() {
                        firePropertyChange(ACCESSIBLE_TEXT_PROPERTY, 
                                           null, pos);
                    }
                };
                SwingUtilities.invokeLater(doFire);
            }
        }

        /**
         * Handles document remove (fire appropriate property change event,
         * which is AccessibleContext.ACCESSIBLE_TEXT_PROPERTY).
         * This tracks the changed offset via the event.
         *
         * @param e the DocumentEvent
         */
        public void changedUpdate(DocumentEvent e) {
            final Integer pos = new Integer (e.getOffset());
            if (SwingUtilities.isEventDispatchThread()) {
                firePropertyChange(ACCESSIBLE_TEXT_PROPERTY, null, pos);
            } else {
                Runnable doFire = new Runnable() {
                    public void run() {
                        firePropertyChange(ACCESSIBLE_TEXT_PROPERTY, 
                                           null, pos);
                    }
                };
                SwingUtilities.invokeLater(doFire);
            }
        }

        /**
         * Gets the state set of the JTextComponent.  
         * The AccessibleStateSet of an object is composed of a set of 
         * unique AccessibleState's.  A change in the AccessibleStateSet 
         * of an object will cause a PropertyChangeEvent to be fired
         * for the AccessibleContext.ACCESSIBLE_STATE_PROPERTY property.
         *
         * @return an instance of AccessibleStateSet containing the
         * current state set of the object
         * @see AccessibleStateSet
         * @see AccessibleState
         * @see #addPropertyChangeListener
         */
        public AccessibleStateSet getAccessibleStateSet() {
            AccessibleStateSet states = super.getAccessibleStateSet();
            if (JTextComponent.this.isEditable()) {
                states.add(AccessibleState.EDITABLE);
            }
            return states;
        }


        /**
         * Gets the role of this object.
         *
         * @return an instance of AccessibleRole describing the role of the 
         * object (AccessibleRole.TEXT)
         * @see AccessibleRole
         */
        public AccessibleRole getAccessibleRole() {
            return AccessibleRole.TEXT;
        }

        /**
         * Get the AccessibleText associated with this object.  In the
         * implementation of the Java Accessibility API for this class, 
         * return this object, which is responsible for implementing the
         * AccessibleText interface on behalf of itself.
         * 
         * @return this object
         */
        public AccessibleText getAccessibleText() {
            return this;
        }


        // --- interface AccessibleText methods ------------------------

        /**
         * Many of these methods are just convenience methods; they
         * just call the equivalent on the parent
         */

        /**
         * Given a point in local coordinates, return the zero-based index
         * of the character under that Point.  If the point is invalid,
         * this method returns -1.
         *
         * @param p the Point in local coordinates
         * @return the zero-based index of the character under Point p.
         */
        public int getIndexAtPoint(Point p) {
            if (p == null) {
                return -1;
            }
            return JTextComponent.this.viewToModel(p);
        }

	    /**
	     * Gets the editor's drawing rectangle.  Stolen
	     * from the unfortunately named 
	     * BasicTextUI.getVisibleEditorRect()
	     *
	     * @return the bounding box for the root view
	     */
	    Rectangle getRootEditorRect() {
	        Rectangle alloc = JTextComponent.this.getBounds();
	        if ((alloc.width > 0) && (alloc.height > 0)) {
		        alloc.x = alloc.y = 0;
		        Insets insets = JTextComponent.this.getInsets();
		        alloc.x += insets.left;
		        alloc.y += insets.top;
		        alloc.width -= insets.left + insets.right;
		        alloc.height -= insets.top + insets.bottom;
		        return alloc;
	        }
	        return null;
	    }

        /**
         * Determines the bounding box of the character at the given
         * index into the string.  The bounds are returned in local
         * coordinates.  If the index is invalid a null rectangle
         * is returned.
         *
         * The screen coordinates returned are "unscrolled coordinates"
         * if the JTextComponent is contained in a JScrollPane in which
         * case the resulting rectangle should be composed with the parent
         * coordinates.  A good algorithm to use is:
         * <nf>
         * Accessible a:
         * AccessibleText at = a.getAccessibleText();
         * AccessibleComponent ac = a.getAccessibleComponent();
         * Rectangle r = at.getCharacterBounds();
         * Point p = ac.getLocation();
         * r.x += p.x;
         * r.y += p.y;
         * </nf>
	 *
	 * Note: the JTextComponent must have a valid size (e.g. have
	 * been added to a parent container whose ancestor container
	 * is a valid top-level window) for this method to be able
	 * to return a meaningful (non-null) value.
         *
         * @param i the index into the String >= 0
         * @return the screen coordinates of the character's bounding box
         */
        public Rectangle getCharacterBounds(int i) {
            if (i < 0 || i > model.getLength()-1) {
                return null;
            }
	    TextUI ui = getUI();
	    if (ui == null) {
		return null;
	    }
	    Rectangle rect = null;
	    Rectangle alloc = getRootEditorRect();
	    if (alloc == null) {
		return null;
	    }
            if (model instanceof AbstractDocument) {
                ((AbstractDocument)model).readLock();
            }
            try {
	        View rootView = ui.getRootView(JTextComponent.this);
	        if (rootView != null) {
	            rootView.setSize(alloc.width, alloc.height);

	            Shape bounds = rootView.modelToView(i,
			            Position.Bias.Forward, i+1, 
			            Position.Bias.Backward, alloc);

	            rect = (bounds instanceof Rectangle) ?
	             (Rectangle)bounds : bounds.getBounds();

		}
            } catch (BadLocationException e) {
            } finally {
                if (model instanceof AbstractDocument) {
                    ((AbstractDocument)model).readUnlock();
                }
            }
	    return rect;
        }

        /**
         * Returns the number of characters (valid indices)
         *
         * @return the number of characters >= 0
         */
        public int getCharCount() {
            return model.getLength();
        }

        /**
         * Returns the zero-based offset of the caret.
         *
         * Note: The character to the right of the caret will have the
         * same index value as the offset (the caret is between
         * two characters).
         *
         * @return the zero-based offset of the caret.
         */
        public int getCaretPosition() {
            return JTextComponent.this.getCaretPosition();
        }

        /**
         * Returns the AttributeSet for a given character (at a given index).
         *
         * @param i the zero-based index into the text
         * @return the AttributeSet of the character
         */
        public AttributeSet getCharacterAttribute(int i) {
            Element e = null;
            if (model instanceof AbstractDocument) {
                ((AbstractDocument)model).readLock();
            }
            try {
                for (e = model.getDefaultRootElement(); ! e.isLeaf(); ) {
                    int index = e.getElementIndex(i);
                    e = e.getElement(index);
                }
            } finally {
                if (model instanceof AbstractDocument) {
                    ((AbstractDocument)model).readUnlock();
                }
            }
            return e.getAttributes();
        }


        /**
         * Returns the start offset within the selected text.
         * If there is no selection, but there is
         * a caret, the start and end offsets will be the same.
         * Return 0 if the text is empty, or the caret position
         * if no selection.
         *
         * @return the index into the text of the start of the selection >= 0
         */
        public int getSelectionStart() {
            return JTextComponent.this.getSelectionStart();
        }

        /**
         * Returns the end offset within the selected text.
         * If there is no selection, but there is
         * a caret, the start and end offsets will be the same.
         * Return 0 if the text is empty, or the caret position
         * if no selection.
         *
         * @return the index into teh text of the end of the selection >= 0
         */
        public int getSelectionEnd() {
            return JTextComponent.this.getSelectionEnd();
        }

        /**
         * Returns the portion of the text that is selected.
         *
         * @return the text, null if no selection
         */
        public String getSelectedText() {
            return JTextComponent.this.getSelectedText();
        }

       /**
         * IndexedSegment extends Segment adding the offset into the
         * the model the <code>Segment</code> was asked for.
         */
        private class IndexedSegment extends Segment {
            /**
             * Offset into the model that the position represents.
             */
            public int modelOffset;
        }


        // TIGER - 4170173
        /**
         * Returns the String at a given index. Whitespace
         * between words is treated as a word.
         *
         * @param part the CHARACTER, WORD, or SENTENCE to retrieve
         * @param index an index within the text
         * @return the letter, word, or sentence.
         *
         */
        public String getAtIndex(int part, int index) {
            return getAtIndex(part, index, 0);
        }


        /**
         * Returns the String after a given index. Whitespace
         * between words is treated as a word.
         *
         * @param part the CHARACTER, WORD, or SENTENCE to retrieve
         * @param index an index within the text
         * @return the letter, word, or sentence.
         */
        public String getAfterIndex(int part, int index) {
            return getAtIndex(part, index, 1);
        }


        /**
         * Returns the String before a given index. Whitespace
         * between words is treated a word.
         *
         * @param part the CHARACTER, WORD, or SENTENCE to retrieve
         * @param index an index within the text
         * @return the letter, word, or sentence.
         */
        public String getBeforeIndex(int part, int index) {
            return getAtIndex(part, index, -1);
        }


        /**
         * Gets the word, sentence, or character at <code>index</code>.
         * If <code>direction</code> is non-null this will find the
         * next/previous word/sentence/character.
         */
        private String getAtIndex(int part, int index, int direction) {
            if (model instanceof AbstractDocument) {
                ((AbstractDocument)model).readLock();
            }
            try {
                if (index < 0 || index >= model.getLength()) {
                    return null;
                }
                switch (part) {
                case AccessibleText.CHARACTER:
                    if (index + direction < model.getLength() &&
                        index + direction >= 0) {
                        return model.getText(index + direction, 1);
                    }
                    break;


                case AccessibleText.WORD:
                case AccessibleText.SENTENCE:
                    IndexedSegment seg = getSegmentAt(part, index);
                    if (seg != null) {
                        if (direction != 0) {
                            int next;


                            if (direction < 0) {
                                next = seg.modelOffset - 1;
                            }
                            else {
                                next = seg.modelOffset + direction * seg.count;
                            }
                            if (next >= 0 && next <= model.getLength()) {
                                seg = getSegmentAt(part, next);
                            }
                            else {
                                seg = null;
                            }
                        }
                        if (seg != null) {
                            return new String(seg.array, seg.offset,
                                                  seg.count);
                        }
                    }
                    break;


                default:
                    break;
                }
            } catch (BadLocationException e) {
            } finally {
                if (model instanceof AbstractDocument) {
                    ((AbstractDocument)model).readUnlock();
                }
            }
            return null;
        }


        /*
         * Returns the paragraph element for the specified index.
         */
        private Element getParagraphElement(int index) {
            if (model instanceof PlainDocument ) {
                PlainDocument sdoc = (PlainDocument)model;
                return sdoc.getParagraphElement(index);
            } else if (model instanceof StyledDocument) {
                StyledDocument sdoc = (StyledDocument)model;
                return sdoc.getParagraphElement(index);
            } else {
                Element para = null;
                for (para = model.getDefaultRootElement(); ! para.isLeaf(); ) {
                    int pos = para.getElementIndex(index);
                    para = para.getElement(pos);
                }
                if (para == null) {
                    return null;
                }
                return para.getParentElement();
            }
        }
        
        /*
         * Returns a <code>Segment</code> containing the paragraph text
         * at <code>index</code>, or null if <code>index</code> isn't
         * valid.
         */
        private IndexedSegment getParagraphElementText(int index)
                                  throws BadLocationException {
            Element para = getParagraphElement(index);


            if (para != null) {
                IndexedSegment segment = new IndexedSegment();
                try {
                    int length = para.getEndOffset() - para.getStartOffset();
                    model.getText(para.getStartOffset(), length, segment);
                } catch (BadLocationException e) {
                    return null;
                }
                segment.modelOffset = para.getStartOffset();
                return segment;
            }
            return null;
        }


        /**
         * Returns the Segment at <code>index</code> representing either
         * the paragraph or sentence as identified by <code>part</code>, or
         * null if a valid paragraph/sentence can't be found. The offset
         * will point to the start of the word/sentence in the array, and
         * the modelOffset will point to the location of the word/sentence
         * in the model.
         */
        private IndexedSegment getSegmentAt(int part, int index) throws
                                  BadLocationException {
            IndexedSegment seg = getParagraphElementText(index);
            if (seg == null) {
                return null;
            }
            BreakIterator iterator;
            switch (part) {
            case AccessibleText.WORD:
                iterator = BreakIterator.getWordInstance(getLocale());
                break;
            case AccessibleText.SENTENCE:
                iterator = BreakIterator.getSentenceInstance(getLocale());
                break;
            default:
                return null;
            }
            seg.first();
            iterator.setText(seg);
            int end = iterator.following(index - seg.modelOffset + seg.offset);
            if (end == BreakIterator.DONE) {
                return null;
            }
            if (end > seg.offset + seg.count) {
                return null;
            }
            int begin = iterator.previous();
            if (begin == BreakIterator.DONE ||
                         begin >= seg.offset + seg.count) {
                return null;
            }
            seg.modelOffset = seg.modelOffset + begin - seg.offset;
            seg.offset = begin;
            seg.count = end - begin;
            return seg;
        }
 
	// begin AccessibleEditableText methods -----

	/**
	 * Returns the AccessibleEditableText interface for
	 * this text component.
	 *
	 * @return the AccessibleEditableText interface
	 * @since 1.4
	 */
	public AccessibleEditableText getAccessibleEditableText() {
	    return this;
	}
	
	/**
	 * Sets the text contents to the specified string.
	 *
	 * @param s the string to set the text contents
	 * @since 1.4
	 */
	public void setTextContents(String s) {
	    JTextComponent.this.setText(s);
	}
	
	/**
	 * Inserts the specified string at the given index
	 *
	 * @param index the index in the text where the string will 
	 * be inserted
	 * @param s the string to insert in the text
	 * @since 1.4
	 */
	public void insertTextAtIndex(int index, String s) {
	    Document doc = JTextComponent.this.getDocument();
	    if (doc != null) {
		try {
		    if (s != null && s.length() > 0) {
			boolean composedTextSaved = saveComposedText(index);
			doc.insertString(index, s, null);
			if (composedTextSaved) {
			    restoreComposedText();
			}
		    }
		} catch (BadLocationException e) {
	            UIManager.getLookAndFeel().provideErrorFeedback(JTextComponent.this);
		}
	    }
	}
	
	/**
	 * Returns the text string between two indices.
	 * 
	 * @param startIndex the starting index in the text
	 * @param endIndex the ending index in the text
	 * @return the text string between the indices
	 * @since 1.4
	 */
	public String getTextRange(int startIndex, int endIndex) {
	    String txt = null;
	    int p0 = Math.min(startIndex, endIndex);
	    int p1 = Math.max(startIndex, endIndex);
	    if (p0 != p1) {
		try {
		    Document doc = JTextComponent.this.getDocument();
		    txt = doc.getText(p0, p1 - p0);
		} catch (BadLocationException e) {
		    throw new IllegalArgumentException(e.getMessage());
		}
	    }
	    return txt;
	}
	
	/**
	 * Deletes the text between two indices
	 *
	 * @param startIndex the starting index in the text
	 * @param endIndex the ending index in the text
	 * @since 1.4
	 */
	public void delete(int startIndex, int endIndex) {
	    if (isEditable() && isEnabled()) {
		try {
		    int p0 = Math.min(startIndex, endIndex);
		    int p1 = Math.max(startIndex, endIndex);
		    if (p0 != p1) {
			Document doc = getDocument();
			doc.remove(p0, p1 - p0);
		    }
		} catch (BadLocationException e) {
		}
	    } else {
		UIManager.getLookAndFeel().provideErrorFeedback(JTextComponent.this);
	    }    
	}
	
	/**
	 * Cuts the text between two indices into the system clipboard.
	 *
	 * @param startIndex the starting index in the text
	 * @param endIndex the ending index in the text
	 * @since 1.4
	 */
	public void cut(int startIndex, int endIndex) {
	    selectText(startIndex, endIndex);
	    JTextComponent.this.cut();
	}
	
	/**
	 * Pastes the text from the system clipboard into the text
	 * starting at the specified index.
	 *
	 * @param startIndex the starting index in the text
	 * @since 1.4
	 */
	public void paste(int startIndex) {
	    setCaretPosition(startIndex);
	    JTextComponent.this.paste();
	}
	
	/**
	 * Replaces the text between two indices with the specified
	 * string.
	 *
	 * @param startIndex the starting index in the text
	 * @param endIndex the ending index in the text
	 * @param s the string to replace the text between two indices
	 * @since 1.4
	 */
	public void replaceText(int startIndex, int endIndex, String s) {
	    selectText(startIndex, endIndex);
	    JTextComponent.this.replaceSelection(s);
	}
	
	/**
	 * Selects the text between two indices.
	 *
	 * @param startIndex the starting index in the text
	 * @param endIndex the ending index in the text
	 * @since 1.4
	 */
	public void selectText(int startIndex, int endIndex) {
	    JTextComponent.this.select(startIndex, endIndex);
	}

        /**
         * Sets attributes for the text between two indices.
         *
         * @param startIndex the starting index in the text
         * @param endIndex the ending index in the text
         * @param as the attribute set
         * @see AttributeSet
	 * @since 1.4
         */
        public void setAttributes(int startIndex, int endIndex, 
            AttributeSet as) {

            // Fixes bug 4487492
            Document doc = JTextComponent.this.getDocument();
            if (doc != null && doc instanceof StyledDocument) {
                StyledDocument sDoc = (StyledDocument)doc;
                int offset = startIndex;
                int length = endIndex - startIndex;
                sDoc.setCharacterAttributes(offset, length, as, true);
            }
        }
	
	// ----- end AccessibleEditableText methods


        // ----- begin AccessibleExtendedText methods

// Probably should replace the helper method getAtIndex() to return
// instead an AccessibleTextSequence also for LINE & ATTRIBUTE_RUN
// and then make the AccessibleText methods get[At|After|Before]Point
// call this new method instead and return only the string portion

        /**
         * Returns the AccessibleTextSequence at a given <code>index</code>.
         * If <code>direction</code> is non-null this will find the
         * next/previous word/sentence/character.
         *
         * @param part the <code>CHARACTER</code>, <code>WORD</code>,
         * <code>SENTENCE</code>, <code>LINE</code> or
         * <code>ATTRIBUTE_RUN</code> to retrieve
         * @param index an index within the text
         * @param direction is either -1, 0, or 1
         * @return an <code>AccessibleTextSequence</code> specifying the text
         * if <code>part</code> and <code>index</code> are valid.  Otherwise,
         * <code>null</code> is returned.
         *
         * @see javax.accessibility.AccessibleText#CHARACTER
         * @see javax.accessibility.AccessibleText#WORD
         * @see javax.accessibility.AccessibleText#SENTENCE
         * @see javax.accessibility.AccessibleExtendedText#LINE
         * @see javax.accessibility.AccessibleExtendedText#ATTRIBUTE_RUN
         *
         * @since 1.6
         */
        private AccessibleTextSequence getSequenceAtIndex(int part, 
            int index, int direction) {
            if (index < 0 || index >= model.getLength()) {
                return null;
            }
            if (direction < -1 || direction > 1) {
                return null;    // direction must be 1, 0, or -1
            }

            switch (part) {
            case AccessibleText.CHARACTER:
                if (model instanceof AbstractDocument) {
                    ((AbstractDocument)model).readLock();
                }
                AccessibleTextSequence charSequence = null;
                try {
                    if (index + direction < model.getLength() &&
                        index + direction >= 0) {
                        charSequence = 
                            new AccessibleTextSequence(index + direction, 
                            index + direction + 1,
                            model.getText(index + direction, 1));
                    } 

                } catch (BadLocationException e) {
                    // we are intentionally silent; our contract says we return
                    // null if there is any failure in this method
                } finally {
                    if (model instanceof AbstractDocument) {
                        ((AbstractDocument)model).readUnlock();
                    }
                }
                return charSequence;

            case AccessibleText.WORD:
            case AccessibleText.SENTENCE:
                if (model instanceof AbstractDocument) {
                    ((AbstractDocument)model).readLock();
                }
                AccessibleTextSequence rangeSequence = null;
                try {
                    IndexedSegment seg = getSegmentAt(part, index);
                    if (seg != null) {
                        if (direction != 0) {
                            int next;

                            if (direction < 0) {
                                next = seg.modelOffset - 1;
                            }
                            else {
                                next = seg.modelOffset + seg.count;
                            }
                            if (next >= 0 && next <= model.getLength()) {
                                seg = getSegmentAt(part, next);
                            }
                            else {
                                seg = null;
                            }
                        }
                        if (seg != null && 
                            (seg.offset + seg.count) <= model.getLength()) {
                            rangeSequence = 
                                new AccessibleTextSequence (seg.offset,
                                seg.offset + seg.count,
                                new String(seg.array, seg.offset, seg.count));
                        } // else we leave rangeSequence set to null
                    }
                } catch(BadLocationException e) {
                    // we are intentionally silent; our contract says we return
                    // null if there is any failure in this method
                } finally {
                    if (model instanceof AbstractDocument) {
                        ((AbstractDocument)model).readUnlock();
                    }
                }
                return rangeSequence;

            case AccessibleExtendedText.LINE:
                AccessibleTextSequence lineSequence = null;
                if (model instanceof AbstractDocument) {
                    ((AbstractDocument)model).readLock();
                }
                try {
                    int startIndex = 
                        Utilities.getRowStart(JTextComponent.this, index);
                    int endIndex = 
                        Utilities.getRowEnd(JTextComponent.this, index);
                    if (startIndex >= 0 && endIndex >= startIndex) {
                        if (direction == 0) {
                            lineSequence = 
                                new AccessibleTextSequence(startIndex, endIndex,
                                    model.getText(startIndex, 
                                        endIndex - startIndex + 1));
                        } else if (direction == -1 && startIndex > 0) {
                            endIndex = 
                                Utilities.getRowEnd(JTextComponent.this, 
                                    startIndex - 1);
                            startIndex = 
                                Utilities.getRowStart(JTextComponent.this, 
                                    startIndex - 1);
                            if (startIndex >= 0 && endIndex >= startIndex) {
                                lineSequence = 
                                    new AccessibleTextSequence(startIndex, 
                                        endIndex,
                                        model.getText(startIndex, 
                                            endIndex - startIndex + 1));
                            }
                        } else if (direction == 1 && 
                         endIndex < model.getLength()) {
                            startIndex = 
                                Utilities.getRowStart(JTextComponent.this, 
                                    endIndex + 1);
                            endIndex = 
                                Utilities.getRowEnd(JTextComponent.this, 
                                    endIndex + 1);
                            if (startIndex >= 0 && endIndex >= startIndex) {
                                lineSequence = 
                                    new AccessibleTextSequence(startIndex, 
                                        endIndex, model.getText(startIndex, 
                                            endIndex - startIndex + 1));
                            }
                        }
                        // already validated 'direction' above...
                    }
                } catch(BadLocationException e) {
                    // we are intentionally silent; our contract says we return
                    // null if there is any failure in this method
                } finally {
                    if (model instanceof AbstractDocument) {
                        ((AbstractDocument)model).readUnlock();
                    }
                }
                return lineSequence;

            case AccessibleExtendedText.ATTRIBUTE_RUN:
                // assumptions: (1) that all characters in a single element 
                // share the same attribute set; (2) that adjacent elements
                // *may* share the same attribute set

                int attributeRunStartIndex, attributeRunEndIndex;
                String runText = null;
                if (model instanceof AbstractDocument) {
                    ((AbstractDocument)model).readLock();
                }

                try {
                    attributeRunStartIndex = attributeRunEndIndex = 
                     Integer.MIN_VALUE;
                    int tempIndex = index;
                    switch (direction) {
                    case -1:
                        // going backwards, so find left edge of this run - 
                        // that'll be the end of the previous run 
                        // (off-by-one counting)
                        attributeRunEndIndex = getRunEdge(index, direction); 
                        // now set ourselves up to find the left edge of the 
                        // prev. run
                        tempIndex = attributeRunEndIndex - 1;
                        break;
                    case 1:
                        // going forward, so find right edge of this run -
                        // that'll be the start of the next run 
                        // (off-by-one counting)
                        attributeRunStartIndex = getRunEdge(index, direction);
                        // now set ourselves up to find the right edge of the 
                        // next run
                        tempIndex = attributeRunStartIndex;
                        break;
                    case 0:
                        // interested in the current run, so nothing special to 
                        // set up in advance...
                        break;
                    default:
                        // only those three values of direction allowed...
                        throw new AssertionError(direction);
                    }

                    // set the unset edge; if neither set then we're getting 
                    // both edges of the current run around our 'index'
                    attributeRunStartIndex = 
                        (attributeRunStartIndex != Integer.MIN_VALUE) ? 
                        attributeRunStartIndex : getRunEdge(tempIndex, -1);
                    attributeRunEndIndex = 
                        (attributeRunEndIndex != Integer.MIN_VALUE) ?
                        attributeRunEndIndex : getRunEdge(tempIndex, 1);

                    runText = model.getText(attributeRunStartIndex, 
                                            attributeRunEndIndex - 
                                            attributeRunStartIndex);
                } catch (BadLocationException e) {
                    // we are intentionally silent; our contract says we return
                    // null if there is any failure in this method
                    return null;
                } finally {
                    if (model instanceof AbstractDocument) {
                        ((AbstractDocument)model).readUnlock();
                    }
                }
                return new AccessibleTextSequence(attributeRunStartIndex,
                                                  attributeRunEndIndex,
                                                  runText);

            default:
                break;
            }
            return null;
        }


        /**
         * Starting at text position <code>index</code>, and going in 
         * <code>direction</code>, return the edge of run that shares the 
         * same <code>AttributeSet</code> and parent element as those at 
         * <code>index</code>.
         *
         * Note: we assume the document is already locked...
         */
        private int getRunEdge(int index, int direction) throws 
         BadLocationException {
            if (index < 0 || index >= model.getLength()) {
                throw new BadLocationException("Location out of bounds", index);
            }
            // locate the Element at index
            Element indexElement = null;
            // locate the Element at our index/offset
            int elementIndex = -1;        // test for initialization
            for (indexElement = model.getDefaultRootElement(); 
                 ! indexElement.isLeaf(); ) {
                elementIndex = indexElement.getElementIndex(index);
                indexElement = indexElement.getElement(elementIndex);
            }
            if (elementIndex == -1) {
                throw new AssertionError(index);
            } 
            // cache the AttributeSet and parentElement atindex 
            AttributeSet indexAS = indexElement.getAttributes(); 
            Element parent = indexElement.getParentElement();

            // find the first Element before/after ours w/the same AttributeSet
            // if we are already at edge of the first element in our parent
            // then return that edge
            Element edgeElement = indexElement;
            switch (direction) {
            case -1:
            case 1:
                int edgeElementIndex = elementIndex;
                int elementCount = parent.getElementCount();
                while ((edgeElementIndex + direction) > 0 && 
                       ((edgeElementIndex + direction) < elementCount) &&
                       parent.getElement(edgeElementIndex
                       + direction).getAttributes().isEqual(indexAS)) {
                    edgeElementIndex += direction;
                }
                edgeElement = parent.getElement(edgeElementIndex);
                break;
            default:
                throw new AssertionError(direction);
            }
            switch (direction) {
            case -1:
                return edgeElement.getStartOffset();
            case 1:
                return edgeElement.getEndOffset();
            default:
                // we already caught this case earlier; this is to satisfy 
                // the compiler...
                return Integer.MIN_VALUE;
            }
        }

        // getTextRange() not needed; defined in AccessibleEditableText

        /**
         * Returns the <code>AccessibleTextSequence</code> at a given 
         * <code>index</code>.
         *
         * @param part the <code>CHARACTER</code>, <code>WORD</code>,
         * <code>SENTENCE</code>, <code>LINE</code> or 
         * <code>ATTRIBUTE_RUN</code> to retrieve
         * @param index an index within the text
         * @return an <code>AccessibleTextSequence</code> specifying the text if
         * <code>part</code> and <code>index</code> are valid.  Otherwise,
         * <code>null</code> is returned
         *
         * @see javax.accessibility.AccessibleText#CHARACTER
         * @see javax.accessibility.AccessibleText#WORD
         * @see javax.accessibility.AccessibleText#SENTENCE
         * @see javax.accessibility.AccessibleExtendedText#LINE
         * @see javax.accessibility.AccessibleExtendedText#ATTRIBUTE_RUN
         *
         * @since 1.6
         */
        public AccessibleTextSequence getTextSequenceAt(int part, int index) {
            return getSequenceAtIndex(part, index, 0);
        }
    
        /**
         * Returns the <code>AccessibleTextSequence</code> after a given 
         * <code>index</code>.
         *
         * @param part the <code>CHARACTER</code>, <code>WORD</code>,
         * <code>SENTENCE</code>, <code>LINE</code> or 
         * <code>ATTRIBUTE_RUN</code> to retrieve
         * @param index an index within the text
         * @return an <code>AccessibleTextSequence</code> specifying the text
         * if <code>part</code> and <code>index</code> are valid.  Otherwise,
         * <code>null</code> is returned
         *
         * @see javax.accessibility.AccessibleText#CHARACTER
         * @see javax.accessibility.AccessibleText#WORD
         * @see javax.accessibility.AccessibleText#SENTENCE
         * @see javax.accessibility.AccessibleExtendedText#LINE
         * @see javax.accessibility.AccessibleExtendedText#ATTRIBUTE_RUN
         *
         * @since 1.6
         */
        public AccessibleTextSequence getTextSequenceAfter(int part, int index) {
            return getSequenceAtIndex(part, index, 1);
        }
    
        /**
         * Returns the <code>AccessibleTextSequence</code> before a given 
         * <code>index</code>.
         *
         * @param part the <code>CHARACTER</code>, <code>WORD</code>,
         * <code>SENTENCE</code>, <code>LINE</code> or 
         * <code>ATTRIBUTE_RUN</code> to retrieve
         * @param index an index within the text
         * @return an <code>AccessibleTextSequence</code> specifying the text 
         * if <code>part</code> and <code>index</code> are valid.  Otherwise,
         * <code>null</code> is returned
         *
         * @see javax.accessibility.AccessibleText#CHARACTER
         * @see javax.accessibility.AccessibleText#WORD
         * @see javax.accessibility.AccessibleText#SENTENCE
         * @see javax.accessibility.AccessibleExtendedText#LINE
         * @see javax.accessibility.AccessibleExtendedText#ATTRIBUTE_RUN
         *
         * @since 1.6
         */
        public AccessibleTextSequence getTextSequenceBefore(int part, int index) {
            return getSequenceAtIndex(part, index, -1);
        }
    
        /**
         * Returns the <code>Rectangle</code> enclosing the text between
         * two indicies.
         *
         * @param startIndex the start index in the text
         * @param endIndex the end index in the text
         * @return the bounding rectangle of the text if the indices are valid.
         * Otherwise, <code>null</code> is returned
         *
         * @since 1.6
         */
        public Rectangle getTextBounds(int startIndex, int endIndex) {
            if (startIndex < 0 || startIndex > model.getLength()-1 ||
                endIndex < 0 || endIndex > model.getLength()-1 ||
                startIndex > endIndex) {
                return null;
            }
            TextUI ui = getUI();
            if (ui == null) {
                return null;
            }
            Rectangle rect = null;
            Rectangle alloc = getRootEditorRect();
            if (alloc == null) {
                return null;
            }
            if (model instanceof AbstractDocument) {
                ((AbstractDocument)model).readLock();
            }
            try {
                View rootView = ui.getRootView(JTextComponent.this);
                if (rootView != null) {
                    Shape bounds = rootView.modelToView(startIndex,
                                    Position.Bias.Forward, endIndex,
                                    Position.Bias.Backward, alloc);

                    rect = (bounds instanceof Rectangle) ?
                     (Rectangle)bounds : bounds.getBounds();

                }
            } catch (BadLocationException e) {
            } finally {
                if (model instanceof AbstractDocument) {
                    ((AbstractDocument)model).readUnlock();
                }
            }
            return rect;
        }
    
        // ----- end AccessibleExtendedText methods


	// --- interface AccessibleAction methods ------------------------

	public AccessibleAction getAccessibleAction() {
	    return this;
	}

	/**
	 * Returns the number of accessible actions available in this object
	 * If there are more than one, the first one is considered the 
	 * "default" action of the object.
	 *
	 * @return the zero-based number of Actions in this object
	 * @since 1.4
	 */
	public int getAccessibleActionCount() {
	    Action [] actions = JTextComponent.this.getActions();
	    return actions.length;
	}
	
	/**
	 * Returns a description of the specified action of the object.
	 *
	 * @param i zero-based index of the actions
	 * @return a String description of the action
	 * @see #getAccessibleActionCount
	 * @since 1.4
	 */
	public String getAccessibleActionDescription(int i) {
	    Action [] actions = JTextComponent.this.getActions();
	    if (i < 0 || i >= actions.length) {
		return null;
	    }
	    return (String)actions[i].getValue(Action.NAME);
	}
	
	/**
	 * Performs the specified Action on the object
	 *
	 * @param i zero-based index of actions
	 * @return true if the action was performed; otherwise false.
	 * @see #getAccessibleActionCount
	 * @since 1.4
	 */
	public boolean doAccessibleAction(int i) {
	    Action [] actions = JTextComponent.this.getActions();
	    if (i < 0 || i >= actions.length) {
		return false;
	    }
            ActionEvent ae =
                new ActionEvent(JTextComponent.this,
                                ActionEvent.ACTION_PERFORMED, null,
                                EventQueue.getMostRecentEventTime(),
                                getCurrentEventModifiers());
	    actions[i].actionPerformed(ae);
	    return true;
	}
	
	// ----- end AccessibleAction methods
	

    }


    // --- serialization ---------------------------------------------

    private void readObject(ObjectInputStream s) 
	throws IOException, ClassNotFoundException 
    {
        s.defaultReadObject();
        caretEvent = new MutableCaretEvent(this);
        addMouseListener(caretEvent);
        addFocusListener(caretEvent);
    }

    // --- member variables ----------------------------------

    /**
     * The document model.
     */
    private Document model;

    /**
     * The caret used to display the insert position
     * and navigate throughout the document. 
     *
     * PENDING(prinz)  
     * This should be serializable, default installed
     * by UI.
     */
    private transient Caret caret;

    /**
     * Object responsible for restricting the cursor navigation.
     */
    private NavigationFilter navigationFilter;

    /**
     * The object responsible for managing highlights.
     *
     * PENDING(prinz)  
     * This should be serializable, default installed
     * by UI.
     */
    private transient Highlighter highlighter;

    /**
     * The current key bindings in effect.
     *
     * PENDING(prinz)  
     * This should be serializable, default installed
     * by UI.
     */
    private transient Keymap keymap;

    private transient MutableCaretEvent caretEvent;
    private Color caretColor;
    private Color selectionColor;
    private Color selectedTextColor;
    private Color disabledTextColor;
    private boolean editable;
    private Insets margin;
    private char focusAccelerator;
    private boolean dragEnabled;

    /**
     * The drop mode for this component.
     */
    private DropMode dropMode = DropMode.USE_SELECTION;

    /**
     * The drop location.
     */
    private transient DropLocation dropLocation;

    /**
     * Represents a drop location for <code>JTextComponent</code>s.
     *
     * @see #getDropLocation
     * @since 1.6
     */
    public static final class DropLocation extends TransferHandler.DropLocation {
        private final int index;
        private final Position.Bias bias;

        private DropLocation(Point p, int index, Position.Bias bias) {
            super(p);
            this.index = index;
            this.bias = bias;
        }

        /**
         * Returns the index where dropped data should be inserted into the
         * associated component. This index represents a position between
         * characters, as would be interpreted by a caret.
         *
         * @return the drop index
         */
        public int getIndex() {
            return index;
        }

        /**
         * Returns the bias for the drop index.
         *
         * @return the drop bias
         */
        public Position.Bias getBias() {
            return bias;
        }

        /**
         * Returns a string representation of this drop location.
         * This method is intended to be used for debugging purposes,
         * and the content and format of the returned string may vary
         * between implementations.
         *
         * @return a string representation of this drop location
         */
        public String toString() {
            return getClass().getName()
                   + "[dropPoint=" + getDropPoint() + ","
                   + "index=" + index + ","
                   + "bias=" + bias + "]";
        }
    }

    /**
     * TransferHandler used if one hasn't been supplied by the UI.
     */
    private static DefaultTransferHandler defaultTransferHandler;

    /**
     * Maps from class name to Boolean indicating if
     * <code>processInputMethodEvent</code> has been overriden.
     */
    private static Map overrideMap;

    /**
     * Returns a string representation of this <code>JTextComponent</code>.
     * This method is intended to be used only for debugging purposes, and the 
     * content and format of the returned string may vary between      
     * implementations. The returned string may be empty but may not 
     * be <code>null</code>.
     * <P>
     * Overriding <code>paramString</code> to provide information about the
     * specific new aspects of the JFC components.
     * 
     * @return  a string representation of this <code>JTextComponent</code>
     */
    protected String paramString() {
        String editableString = (editable ?
				 "true" : "false");
        String caretColorString = (caretColor != null ?
				   caretColor.toString() : "");
        String selectionColorString = (selectionColor != null ?
				       selectionColor.toString() : "");
        String selectedTextColorString = (selectedTextColor != null ?
					  selectedTextColor.toString() : "");
        String disabledTextColorString = (disabledTextColor != null ?
					  disabledTextColor.toString() : "");
        String marginString = (margin != null ?
			       margin.toString() : "");

        return super.paramString() +
        ",caretColor=" + caretColorString +
        ",disabledTextColor=" + disabledTextColorString +
        ",editable=" + editableString +
        ",margin=" + marginString +
        ",selectedTextColor=" + selectedTextColorString +
        ",selectionColor=" + selectionColorString;
    }


    /**
     * A Simple TransferHandler that exports the data as a String, and
     * imports the data from the String clipboard.  This is only used
     * if the UI hasn't supplied one, which would only happen if someone
     * hasn't subclassed Basic.
     */
    static class DefaultTransferHandler extends TransferHandler implements
                                        UIResource {
        public void exportToClipboard(JComponent comp, Clipboard clipboard,
                                      int action) throws IllegalStateException {
            if (comp instanceof JTextComponent) {
                JTextComponent text = (JTextComponent)comp;
                int p0 = text.getSelectionStart();
                int p1 = text.getSelectionEnd();
                if (p0 != p1) {
                    try {
                        Document doc = text.getDocument();
                        String srcData = doc.getText(p0, p1 - p0);
                        StringSelection contents =new StringSelection(srcData);

                        // this may throw an IllegalStateException,
                        // but it will be caught and handled in the
                        // action that invoked this method
                        clipboard.setContents(contents, null);

                        if (action == TransferHandler.MOVE) {
                            doc.remove(p0, p1 - p0);
                        }
                    } catch (BadLocationException ble) {}
                }
            }
        }
        public boolean importData(JComponent comp, Transferable t) {
            if (comp instanceof JTextComponent) {
                DataFlavor flavor = getFlavor(t.getTransferDataFlavors());

                if (flavor != null) {
		    InputContext ic = comp.getInputContext();
		    if (ic != null) {
			ic.endComposition();
		    }
                    try {
                        String data = (String)t.getTransferData(flavor);

                        ((JTextComponent)comp).replaceSelection(data);
                        return true;
                    } catch (UnsupportedFlavorException ufe) {
                    } catch (IOException ioe) {
                    }
                }
            }
            return false;
        }
        public boolean canImport(JComponent comp,
                                 DataFlavor[] transferFlavors) {
            JTextComponent c = (JTextComponent)comp;
            if (!(c.isEditable() && c.isEnabled())) {
                return false;
            }
            return (getFlavor(transferFlavors) != null);
        }
        public int getSourceActions(JComponent c) {
            return NONE;
        }
        private DataFlavor getFlavor(DataFlavor[] flavors) {
            if (flavors != null) {
                for (int counter = 0; counter < flavors.length; counter++) {
                    if (flavors[counter].equals(DataFlavor.stringFlavor)) {
                        return flavors[counter];
                    }
                }
            }
            return null;
        }
    }

    /**
     * Returns the JTextComponent that most recently had focus. The returned
     * value may currently have focus.
     */
    static final JTextComponent getFocusedComponent() {
        return (JTextComponent)AppContext.getAppContext().
            get(FOCUSED_COMPONENT);
    }

    private int getCurrentEventModifiers() {
        int modifiers = 0;
        AWTEvent currentEvent = EventQueue.getCurrentEvent();
        if (currentEvent instanceof InputEvent) {
            modifiers = ((InputEvent)currentEvent).getModifiers();
        } else if (currentEvent instanceof ActionEvent) {
            modifiers = ((ActionEvent)currentEvent).getModifiers();
        }
        return modifiers;
    }

    private static final Object KEYMAP_TABLE = 
        new StringBuilder("JTextComponent_KeymapTable");
    private JTextComponent editor;
    //
    // member variables used for on-the-spot input method 
    // editing style support
    // 
    private transient InputMethodRequests inputMethodRequestsHandler;
    private SimpleAttributeSet composedTextAttribute;
    private String composedTextContent;
    private Position composedTextStart;
    private Position composedTextEnd;    
    private Position latestCommittedTextStart;
    private Position latestCommittedTextEnd;
    private ComposedTextCaret composedTextCaret;
    private transient Caret originalCaret;
    /**
     * Set to true after the check for the override of processInputMethodEvent
     * has been checked.
     */
    private boolean checkedInputOverride;
    private boolean needToSendKeyTypedEvent;

    static class DefaultKeymap implements Keymap {

        DefaultKeymap(String nm, Keymap parent) {
            this.nm = nm; 
            this.parent = parent;
            bindings = new Hashtable();
        }

        /**
         * Fetch the default action to fire if a 
         * key is typed (ie a KEY_TYPED KeyEvent is received)
         * and there is no binding for it.  Typically this
         * would be some action that inserts text so that 
         * the keymap doesn't require an action for each 
         * possible key.
         */
        public Action getDefaultAction() {
            if (defaultAction != null) {
                return defaultAction;
            }
            return (parent != null) ? parent.getDefaultAction() : null;
        }

        /**
         * Set the default action to fire if a key is typed.
         */
        public void setDefaultAction(Action a) {
            defaultAction = a;
        }

        public String getName() {
            return nm;
        }

        public Action getAction(KeyStroke key) {
            Action a = (Action) bindings.get(key);
            if ((a == null) && (parent != null)) {
                a = parent.getAction(key);
            }
            return a;
        }

        public KeyStroke[] getBoundKeyStrokes() {
            KeyStroke[] keys = new KeyStroke[bindings.size()];
            int i = 0;
            for (Enumeration e = bindings.keys() ; e.hasMoreElements() ;) {
                keys[i++] = (KeyStroke) e.nextElement();
            }
            return keys;
        } 

        public Action[] getBoundActions() {
            Action[] actions = new Action[bindings.size()];
            int i = 0;
            for (Enumeration e = bindings.elements() ; e.hasMoreElements() ;) {
                actions[i++] = (Action) e.nextElement();
            }
            return actions;
        } 

        public KeyStroke[] getKeyStrokesForAction(Action a) {
	    if (a == null) {
		return null;
	    }
	    KeyStroke[] retValue = null;
	    // Determine local bindings first.
	    Vector keyStrokes = null;
	    for (Enumeration enum_ = bindings.keys();
		 enum_.hasMoreElements();) {
		Object key = enum_.nextElement();
		if (bindings.get(key) == a) {
		    if (keyStrokes == null) {
			keyStrokes = new Vector();
		    }
		    keyStrokes.addElement(key);
		}
	    }
	    // See if the parent has any.
	    if (parent != null) {
		KeyStroke[] pStrokes = parent.getKeyStrokesForAction(a);
		if (pStrokes != null) {
		    // Remove any bindings defined in the parent that
		    // are locally defined.
		    int rCount = 0;
		    for (int counter = pStrokes.length - 1; counter >= 0;
			 counter--) {
			if (isLocallyDefined(pStrokes[counter])) {
			    pStrokes[counter] = null;
			    rCount++;
			}
		    }
		    if (rCount > 0 && rCount < pStrokes.length) {
			if (keyStrokes == null) {
			    keyStrokes = new Vector();
			}
			for (int counter = pStrokes.length - 1; counter >= 0;
			     counter--) {
			    if (pStrokes[counter] != null) {
				keyStrokes.addElement(pStrokes[counter]);
			    }
			}
		    }
		    else if (rCount == 0) {
			if (keyStrokes == null) {
			    retValue = pStrokes;
			}
			else {
			    retValue = new KeyStroke[keyStrokes.size() +
						    pStrokes.length];
			    keyStrokes.copyInto(retValue);
			    System.arraycopy(pStrokes, 0, retValue,
					keyStrokes.size(), pStrokes.length);
			    keyStrokes = null;
			}
		    }
		}
	    }
	    if (keyStrokes != null) {
		retValue = new KeyStroke[keyStrokes.size()];
		keyStrokes.copyInto(retValue);
	    }
            return retValue;
        }

        public boolean isLocallyDefined(KeyStroke key) {
            return bindings.containsKey(key);
        }

        public void addActionForKeyStroke(KeyStroke key, Action a) {
            bindings.put(key, a);
        }

        public void removeKeyStrokeBinding(KeyStroke key) {
            bindings.remove(key);
        }

        public void removeBindings() {
            bindings.clear();
        }

        public Keymap getResolveParent() {
            return parent;
        }

        public void setResolveParent(Keymap parent) {
            this.parent = parent;
        }

        /**
         * String representation of the keymap... potentially 
         * a very long string.
         */
        public String toString() {
            return "Keymap[" + nm + "]" + bindings;
        }

        String nm;
        Keymap parent;
        Hashtable bindings;
        Action defaultAction;
    }


    /**
     * KeymapWrapper wraps a Keymap inside an InputMap. For KeymapWrapper
     * to be useful it must be used with a KeymapActionMap.
     * KeymapWrapper for the most part, is an InputMap with two parents.
     * The first parent visited is ALWAYS the Keymap, with the second
     * parent being the parent inherited from InputMap. If
     * <code>keymap.getAction</code> returns null, implying the Keymap
     * does not have a binding for the KeyStroke,
     * the parent is then visited. If the Keymap has a binding, the 
     * Action is returned, if not and the KeyStroke represents a
     * KeyTyped event and the Keymap has a defaultAction,
     * <code>DefaultActionKey</code> is returned.
     * <p>KeymapActionMap is then able to transate the object passed in
     * to either message the Keymap, or message its default implementation.
     */
    static class KeymapWrapper extends InputMap {
	static final Object DefaultActionKey = new Object();

	private Keymap keymap;

	KeymapWrapper(Keymap keymap) {
	    this.keymap = keymap;
	}

	public KeyStroke[] keys() {
	    KeyStroke[] sKeys = super.keys();
	    KeyStroke[] keymapKeys = keymap.getBoundKeyStrokes();
	    int sCount = (sKeys == null) ? 0 : sKeys.length;
	    int keymapCount = (keymapKeys == null) ? 0 : keymapKeys.length;
	    if (sCount == 0) {
		return keymapKeys;
	    }
	    if (keymapCount == 0) {
		return sKeys;
	    }
	    KeyStroke[] retValue = new KeyStroke[sCount + keymapCount];
	    // There may be some duplication here...
	    System.arraycopy(sKeys, 0, retValue, 0, sCount);
	    System.arraycopy(keymapKeys, 0, retValue, sCount, keymapCount);
	    return retValue;
	}

	public int size() {
	    // There may be some duplication here...
	    KeyStroke[] keymapStrokes = keymap.getBoundKeyStrokes();
	    int keymapCount = (keymapStrokes == null) ? 0:
		               keymapStrokes.length;
	    return super.size() + keymapCount;
	}

	public Object get(KeyStroke keyStroke) {
	    Object retValue = keymap.getAction(keyStroke);
            if (retValue == null) {
		retValue = super.get(keyStroke);
		if (retValue == null &&
		    keyStroke.getKeyChar() != KeyEvent.CHAR_UNDEFINED &&
		    keymap.getDefaultAction() != null) {
		    // Implies this is a KeyTyped event, use the default
		    // action.
		    retValue = DefaultActionKey;
		}
	    }
	    return retValue;
	}
    }


    /**
     * Wraps a Keymap inside an ActionMap. This is used with
     * a KeymapWrapper. If <code>get</code> is passed in
     * <code>KeymapWrapper.DefaultActionKey</code>, the default action is
     * returned, otherwise if the key is an Action, it is returned.
     */
    static class KeymapActionMap extends ActionMap {
	private Keymap keymap;

	KeymapActionMap(Keymap keymap) {
	    this.keymap = keymap;
	}

	public Object[] keys() {
	    Object[] sKeys = super.keys();
	    Object[] keymapKeys = keymap.getBoundActions();
	    int sCount = (sKeys == null) ? 0 : sKeys.length;
	    int keymapCount = (keymapKeys == null) ? 0 : keymapKeys.length;
	    boolean hasDefault = (keymap.getDefaultAction() != null);
	    if (hasDefault) {
		keymapCount++;
	    }
	    if (sCount == 0) {
		if (hasDefault) {
		    Object[] retValue = new Object[keymapCount];
		    if (keymapCount > 1) {
			System.arraycopy(keymapKeys, 0, retValue, 0,
					 keymapCount - 1);
		    }
		    retValue[keymapCount - 1] = KeymapWrapper.DefaultActionKey;
		    return retValue;
		}
		return keymapKeys;
	    }
	    if (keymapCount == 0) {
		return sKeys;
	    }
	    Object[] retValue = new Object[sCount + keymapCount];
	    // There may be some duplication here...
	    System.arraycopy(sKeys, 0, retValue, 0, sCount);
	    if (hasDefault) {
		if (keymapCount > 1) {
		    System.arraycopy(keymapKeys, 0, retValue, sCount,
				     keymapCount - 1);
		}
		retValue[sCount + keymapCount - 1] = KeymapWrapper.
		                                 DefaultActionKey;
	    }
	    else {
		System.arraycopy(keymapKeys, 0, retValue, sCount, keymapCount);
	    }
	    return retValue;
	}

	public int size() {
	    // There may be some duplication here...
	    Object[] actions = keymap.getBoundActions();
	    int keymapCount = (actions == null) ? 0 : actions.length;
	    if (keymap.getDefaultAction() != null) {
		keymapCount++;
	    }
	    return super.size() + keymapCount;
	}

	public Action get(Object key) {
	    Action retValue = super.get(key);
	    if (retValue == null) {
		// Try the Keymap.
		if (key == KeymapWrapper.DefaultActionKey) {
		    retValue = keymap.getDefaultAction();
		}
		else if (key instanceof Action) {
		    // This is a little iffy, technically an Action is
		    // a valid Key. We're assuming the Action came from
		    // the InputMap though.
		    retValue = (Action)key;
		}
	    }
	    return retValue;
	}
    }

    private static final Object FOCUSED_COMPONENT = 
        new StringBuilder("JTextComponent_FocusedComponent");
    
    /**
     * The default keymap that will be shared by all
     * <code>JTextComponent</code> instances unless they
     * have had a different keymap set. 
     */
    public static final String DEFAULT_KEYMAP = "default";

    /**
     * Event to use when firing a notification of change to caret 
     * position.  This is mutable so that the event can be reused
     * since caret events can be fairly high in bandwidth.
     */
    static class MutableCaretEvent extends CaretEvent implements ChangeListener, FocusListener, MouseListener {

        MutableCaretEvent(JTextComponent c) {
            super(c);
        }

        final void fire() {
            JTextComponent c = (JTextComponent) getSource();
            if (c != null) {
                Caret caret = c.getCaret();
                dot = caret.getDot();
                mark = caret.getMark();
                c.fireCaretUpdate(this);
            }
        }

        public final String toString() {
            return "dot=" + dot + "," + "mark=" + mark;
        }

        // --- CaretEvent methods -----------------------

        public final int getDot() {
            return dot;
        }

        public final int getMark() {
            return mark;
        }

        // --- ChangeListener methods -------------------

        public final void stateChanged(ChangeEvent e) {
            if (! dragActive) {
                fire();
            }
        }

        // --- FocusListener methods -----------------------------------
        public void focusGained(FocusEvent fe) {
            AppContext.getAppContext().put(FOCUSED_COMPONENT,
                                           fe.getSource());
        }

        public void focusLost(FocusEvent fe) {
        }

        // --- MouseListener methods -----------------------------------
    
        /**
         * Requests focus on the associated
         * text component, and try to set the cursor position.
         *
         * @param e the mouse event
         * @see MouseListener#mousePressed
         */
        public final void mousePressed(MouseEvent e) {
            dragActive = true;
        }

        /**
         * Called when the mouse is released.
         *
         * @param e the mouse event
         * @see MouseListener#mouseReleased
         */
        public final void mouseReleased(MouseEvent e) {
            dragActive = false;
            fire();
        }

        public final void mouseClicked(MouseEvent e) {
        }

        public final void mouseEntered(MouseEvent e) {
        }

        public final void mouseExited(MouseEvent e) {
        }

        private boolean dragActive;
        private int dot;
        private int mark;
    }

    //
    // Process any input method events that the component itself 
    // recognizes. The default on-the-spot handling for input method 
    // composed(uncommitted) text is done here after all input 
    // method listeners get called for stealing the events.
    //
    protected void processInputMethodEvent(InputMethodEvent e) {
	// let listeners handle the events
	super.processInputMethodEvent(e);

	if (!e.isConsumed()) {
            if (! isEditable()) {
                return;
            } else {
  	        switch (e.getID()) {
		case InputMethodEvent.INPUT_METHOD_TEXT_CHANGED:
		    replaceInputMethodText(e);

		    // fall through

		case InputMethodEvent.CARET_POSITION_CHANGED:
		    setInputMethodCaretPosition(e);
		    break;
		}
	    }

	    e.consume();
	}
    }

    //
    // Overrides this method to become an active input method client.
    //
    public InputMethodRequests getInputMethodRequests() {
    	if (inputMethodRequestsHandler == null) {
	    inputMethodRequestsHandler = 
	        (InputMethodRequests)new InputMethodRequestsHandler();
	    Document doc = getDocument();
	    if (doc != null) {
		doc.addDocumentListener((DocumentListener)inputMethodRequestsHandler);
	    }
	}

	return inputMethodRequestsHandler;
    }

    //
    // Overrides this method to watch the listener installed.
    //
    public void addInputMethodListener(InputMethodListener l) {
    	super.addInputMethodListener(l);
	if (l != null) {
	    needToSendKeyTypedEvent = false;
            checkedInputOverride = true;
	}
    }
    

    //
    // Default implementation of the InputMethodRequests interface.
    //
    class InputMethodRequestsHandler implements InputMethodRequests, DocumentListener {

	// --- InputMethodRequests methods ---
	
	public AttributedCharacterIterator cancelLatestCommittedText(
						Attribute[] attributes) {
	    Document doc = getDocument();
	    if ((doc != null) && (latestCommittedTextStart != null) 
                && (!latestCommittedTextStart.equals(latestCommittedTextEnd))) {
		try {
		    int startIndex = latestCommittedTextStart.getOffset();
                    int endIndex = latestCommittedTextEnd.getOffset();
		    String latestCommittedText = 
                        doc.getText(startIndex, endIndex - startIndex);
		    doc.remove(startIndex, endIndex - startIndex);
		    return new AttributedString(latestCommittedText).getIterator();
		} catch (BadLocationException ble) {}
	    }
	    return null;
    	}

    	public AttributedCharacterIterator getCommittedText(int beginIndex, 
					int endIndex, Attribute[] attributes) {
	    int composedStartIndex = 0;
	    int composedEndIndex = 0;
	    if (composedTextExists()) {
		composedStartIndex = composedTextStart.getOffset();
		composedEndIndex = composedTextEnd.getOffset();
	    }

	    String committed;
	    try {
		if (beginIndex < composedStartIndex) {
		    if (endIndex <= composedStartIndex) {
			committed = getText(beginIndex, endIndex - beginIndex);
		    } else {
			int firstPartLength = composedStartIndex - beginIndex;
			committed = getText(beginIndex, firstPartLength) +
			    getText(composedEndIndex, endIndex - beginIndex - firstPartLength);
		    }
		} else {
		    committed = getText(beginIndex + (composedEndIndex - composedStartIndex),
		                        endIndex - beginIndex);
		}
	    } catch (BadLocationException ble) {
		throw new IllegalArgumentException("Invalid range");
	    }
	    return new AttributedString(committed).getIterator();
    	}

    	public int getCommittedTextLength() {
	    Document doc = getDocument();
	    int length = 0;
	    if (doc != null) {
		length = doc.getLength();
		if (composedTextContent != null) {
                    if (composedTextEnd == null
                          || composedTextStart == null) {
                        /* 
                         * fix for : 6355666
                         * this is the case when this method is invoked
                         * from DocumentListener. At this point 
                         * composedTextEnd and composedTextStart are
                         * not defined yet.
                         */ 
                        length -= composedTextContent.length();
                    } else {
                        length -= composedTextEnd.getOffset() - 
                            composedTextStart.getOffset();
                    }
		}
            }
	    return length;
    	}

    	public int getInsertPositionOffset() {
	    int composedStartIndex = 0;
	    int composedEndIndex = 0;
	    if (composedTextExists()) {
		composedStartIndex = composedTextStart.getOffset();
		composedEndIndex = composedTextEnd.getOffset();
	    }
	    int caretIndex = getCaretPosition();

	    if (caretIndex < composedStartIndex) {
		return caretIndex;
	    } else if (caretIndex < composedEndIndex) {
		return composedStartIndex;
	    } else {
		return caretIndex - (composedEndIndex - composedStartIndex);
	    }
    	}

    	public TextHitInfo getLocationOffset(int x, int y) {
	    if (composedTextAttribute == null) {
	        return null;
	    } else { 
	        Point p = getLocationOnScreen();
	        p.x = x - p.x;
	        p.y = y - p.y;
	        int pos = viewToModel(p);
	        if ((pos >= composedTextStart.getOffset()) && 
		    (pos <= composedTextEnd.getOffset())) {
	            return TextHitInfo.leading(pos - composedTextStart.getOffset());
	        } else {
	            return null;
	        }
	    }	
    	}

    	public Rectangle getTextLocation(TextHitInfo offset) {
	    Rectangle r;
		
	    try {
	        r = modelToView(getCaretPosition());
		if (r != null) {
		    Point p = getLocationOnScreen();
		    r.translate(p.x, p.y);
		}
	    } catch (BadLocationException ble) {
	        r = null;
	    }

	    if (r == null)
	        r = new Rectangle();

	    return r;
	}

    	public AttributedCharacterIterator getSelectedText(
						Attribute[] attributes) {
	    String selection = JTextComponent.this.getSelectedText();
	    if (selection != null) {
	        return new AttributedString(selection).getIterator();
	    } else {
	        return null;
	    }
    	}

	// --- DocumentListener methods ---
	
	public void changedUpdate(DocumentEvent e) {
	    latestCommittedTextStart = latestCommittedTextEnd = null;
	}

	public void insertUpdate(DocumentEvent e) {
	    latestCommittedTextStart = latestCommittedTextEnd = null;
	}

	public void removeUpdate(DocumentEvent e) {
	    latestCommittedTextStart = latestCommittedTextEnd = null;
	}
    }

    //
    // Replaces the current input method (composed) text according to
    // the passed input method event. This method also inserts the 
    // committed text into the document. 
    //
    private void replaceInputMethodText(InputMethodEvent e) {
    	int commitCount = e.getCommittedCharacterCount();
	AttributedCharacterIterator text = e.getText();
	int composedTextIndex;

	// old composed text deletion
	Document doc = getDocument();
	if (composedTextExists()) {
	    try {	
	        doc.remove(composedTextStart.getOffset(), 
                           composedTextEnd.getOffset() - 
                           composedTextStart.getOffset());
	    } catch (BadLocationException ble) {}
	    composedTextStart = composedTextEnd = null;
	    composedTextAttribute = null;
	    composedTextContent = null;
	}
	
	if (text != null) {
	    text.first();
	    int committedTextStartIndex = 0;
	    int committedTextEndIndex = 0;

	    // committed text insertion
	    if (commitCount > 0) {
		// Remember latest committed text start index
		committedTextStartIndex = caret.getDot();

		// Need to generate KeyTyped events for the committed text for components
		// that are not aware they are active input method clients.
		if (shouldSynthensizeKeyEvents()) {
		    for (char c = text.current(); commitCount > 0; 
		         c = text.next(), commitCount--) {
			KeyEvent ke = new KeyEvent(this, KeyEvent.KEY_TYPED, 
						   EventQueue.getMostRecentEventTime(),
						   0, KeyEvent.VK_UNDEFINED, c);
			processKeyEvent(ke);
		    }
		} else {
		    StringBuffer strBuf = new StringBuffer();
		    for (char c = text.current(); commitCount > 0; 
		         c = text.next(), commitCount--) {
			strBuf.append(c);
		    }
		
		    // map it to an ActionEvent
		    mapCommittedTextToAction(new String(strBuf));
		}
		
		// Remember latest committed text end index 
		committedTextEndIndex = caret.getDot();
	    }

	    // new composed text insertion
	    composedTextIndex = text.getIndex();
	    if (composedTextIndex < text.getEndIndex()) {
		createComposedTextAttribute(composedTextIndex, text);
		try {	
		    replaceSelection(null);
		    doc.insertString(caret.getDot(), composedTextContent, 
		    			composedTextAttribute);
		    composedTextStart = doc.createPosition(caret.getDot() -
						composedTextContent.length());
                    composedTextEnd = doc.createPosition(caret.getDot());
		} catch (BadLocationException ble) {
	            composedTextStart = composedTextEnd = null;
	            composedTextAttribute = null;
	            composedTextContent = null;
		}	
	    }

	    // Save the latest committed text information
	    if (committedTextStartIndex != committedTextEndIndex) {
		try {	
		    latestCommittedTextStart = doc.
                        createPosition(committedTextStartIndex);
                    latestCommittedTextEnd = doc.
                        createPosition(committedTextEndIndex);
		} catch (BadLocationException ble) {
		    latestCommittedTextStart = 
                        latestCommittedTextEnd = null;
		}
	    } else {
		latestCommittedTextStart = 
                    latestCommittedTextEnd = null;
	    }
	}
    }

    private void createComposedTextAttribute(int composedIndex, 
    					AttributedCharacterIterator text) {
	Document doc = getDocument();
        StringBuffer strBuf = new StringBuffer();

	// create attributed string with no attributes
	for (char c = text.setIndex(composedIndex); 
             c != CharacterIterator.DONE; c = text.next()) {
	    strBuf.append(c);
	}
	
	composedTextContent = new String(strBuf);	
	composedTextAttribute = new SimpleAttributeSet();	
	composedTextAttribute.addAttribute(StyleConstants.ComposedTextAttribute, 
		new AttributedString(text, composedIndex, text.getEndIndex()));
    }

    private boolean saveComposedText(int pos) {
	if (composedTextExists()) {
	    int start = composedTextStart.getOffset();
	    int len = composedTextEnd.getOffset() - 
                composedTextStart.getOffset();
	    if (pos >= start && pos <= start + len) {
		try {	
		    getDocument().remove(start, len);
		    return true;
		} catch (BadLocationException ble) {}
	    }
	}
	return false;
    }

    private void restoreComposedText() {
	Document doc = getDocument();
	try {
	    doc.insertString(caret.getDot(),
                             composedTextContent, 
		    	     composedTextAttribute);
	    composedTextStart = doc.createPosition(caret.getDot() - 
				composedTextContent.length());
            composedTextEnd = doc.createPosition(caret.getDot());
	} catch (BadLocationException ble) {}
    }
    
    //
    // Map committed text to an ActionEvent. If the committed text length is 1,
    // treat it as a KeyStroke, otherwise or there is no KeyStroke defined, 
    // treat it just as a default action.
    //
    private void mapCommittedTextToAction(String committedText) {
        Keymap binding = getKeymap();
        if (binding != null) {
            Action a = null;
            if (committedText.length() == 1) {
		KeyStroke k = KeyStroke.getKeyStroke(committedText.charAt(0));
                a = binding.getAction(k);
	    }

	    if (a == null) { 
	        a = binding.getDefaultAction();
	    }

            if (a != null) {
                ActionEvent ae =
                    new ActionEvent(this, ActionEvent.ACTION_PERFORMED, 
                                    committedText,
                                    EventQueue.getMostRecentEventTime(),
                                    getCurrentEventModifiers());
                a.actionPerformed(ae);
            }
        }
    }

    //
    // Sets the caret position according to the passed input method
    // event. Also, sets/resets composed text caret appropriately.
    //
    private void setInputMethodCaretPosition(InputMethodEvent e) {
	int dot;
	
	if (composedTextExists()) {
	    dot = composedTextStart.getOffset();
	    if (!(caret instanceof ComposedTextCaret)) {
		if (composedTextCaret == null) {
		    composedTextCaret = new ComposedTextCaret();
		}
		originalCaret = caret;	
		// Sets composed text caret
	        exchangeCaret(originalCaret, composedTextCaret);
	    }

	    TextHitInfo caretPos = e.getCaret();
	    if (caretPos != null) {
		int index = caretPos.getInsertionIndex();
		dot += index;
		if (index == 0) {
		    // Scroll the component if needed so that the composed text
		    // becomes visible.
		    try {
			Rectangle d = modelToView(dot);
			Rectangle end = modelToView(composedTextEnd.getOffset());
			Rectangle b = getBounds(); 
			d.x += Math.min(end.x - d.x, b.width);
			scrollRectToVisible(d);
		    } catch (BadLocationException ble) {}
		}
	    }
	    caret.setDot(dot);
	} else if (caret instanceof ComposedTextCaret) {
	    dot = caret.getDot();
	    // Restores original caret
	    exchangeCaret(caret, originalCaret);
	    caret.setDot(dot);
	}
    }

    private void exchangeCaret(Caret oldCaret, Caret newCaret) {
	int blinkRate = oldCaret.getBlinkRate();
	setCaret(newCaret);
	caret.setBlinkRate(blinkRate);
	caret.setVisible(hasFocus());
    }

    /**
     * Returns true if KeyEvents should be synthesized from an InputEvent.
     */
    private boolean shouldSynthensizeKeyEvents() {
        if (!checkedInputOverride) {
            checkedInputOverride = true;
            needToSendKeyTypedEvent =
                             !isProcessInputMethodEventOverridden();
        }
        return needToSendKeyTypedEvent;
    }

    //
    // Checks whether the client code overrides processInputMethodEvent.  If it is overridden,
    // need not to generate KeyTyped events for committed text. If it's not, behave as an 
    // passive input method client.
    //
    private boolean isProcessInputMethodEventOverridden() {
        if (overrideMap == null) {
            overrideMap = Collections.synchronizedMap(new HashMap());
        }
        Boolean retValue = (Boolean)overrideMap.get(getClass().getName());

        if (retValue != null) {
            return retValue.booleanValue();
        }
	Boolean ret = (Boolean)AccessController.doPrivileged(new
                       PrivilegedAction() {
            public Object run() {
                return isProcessInputMethodEventOverridden(
                                JTextComponent.this.getClass());
            }
        });

	return ret.booleanValue();
    }

    //
    // Checks whether a composed text in this text component
    //
    boolean composedTextExists() {
	return (composedTextStart != null);
    }

    //
    // Caret implementation for editing the composed text.
    //
    class ComposedTextCaret extends DefaultCaret implements Serializable {
	Color bg;

	//	
	// Get the background color of the component
	//	
	public void install(JTextComponent c) {
	    super.install(c);

	    Document doc = c.getDocument();
	    if (doc instanceof StyledDocument) {
		StyledDocument sDoc = (StyledDocument)doc;
		Element elem = sDoc.getCharacterElement(c.composedTextStart.getOffset());
	        AttributeSet attr = elem.getAttributes();
	        bg = sDoc.getBackground(attr);
	    }
	
	    if (bg == null) {
	        bg = c.getBackground();
	    }
	}
        
	//
	// Draw caret in XOR mode.
        // 
	public void paint(Graphics g) {
	    if(isVisible()) {
	        try {
		    Rectangle r = component.modelToView(getDot());
		    g.setXORMode(bg);
		    g.drawLine(r.x, r.y, r.x, r.y + r.height - 1);
		    g.setPaintMode();
	        } catch (BadLocationException e) {
		    // can't render I guess
		    //System.err.println("Can't render cursor");
	        }
	    }
	}

	//
	// If some area other than the composed text is clicked by mouse,
	// issue endComposition() to force commit the composed text.
	//
	protected void positionCaret(MouseEvent me) {
	    JTextComponent host = component;
	    Point pt = new Point(me.getX(), me.getY());
	    int offset = host.viewToModel(pt);
	    int composedStartIndex = host.composedTextStart.getOffset();
	    if ((offset < composedStartIndex) ||
	        (offset > composedTextEnd.getOffset())) {
		try {
		    // Issue endComposition
		    Position newPos = host.getDocument().createPosition(offset); 
		    host.getInputContext().endComposition();

		    // Post a caret positioning runnable to assure that the positioning
		    // occurs *after* committing the composed text.
		    EventQueue.invokeLater(new DoSetCaretPosition(host, newPos));
		} catch (BadLocationException ble) {
		    System.err.println(ble);
		}
	    } else {
	        // Normal processing
	        super.positionCaret(me);
	    }
	}
    }

    //
    // Runnable class for invokeLater() to set caret position later.
    //
    private class DoSetCaretPosition implements Runnable {
        JTextComponent host; 
	Position newPos;

	DoSetCaretPosition(JTextComponent host, Position newPos) {
	    this.host = host;
	    this.newPos = newPos;
	}

	public void run() {
	    host.setCaretPosition(newPos.getOffset());
	}
    }
}

Generated By: JavaOnTracks Doclet 0.1.4     ©Thibaut Colar