summaryrefslogtreecommitdiff
path: root/libjava/classpath/javax/swing/plaf/basic/BasicSliderUI.java
blob: b9d5643725abb07a78405cf44a5d98375bdf8599 (plain)
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
/* BasicSliderUI.java --
   Copyright (C) 2004, 2005, 2006,  Free Software Foundation, Inc.

This file is part of GNU Classpath.

GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.

GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version. */


package javax.swing.plaf.basic;

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Polygon;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Dictionary;
import java.util.Enumeration;

import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.BoundedRangeModel;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JSlider;
import javax.swing.LookAndFeel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.MouseInputAdapter;
import javax.swing.plaf.ActionMapUIResource;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.SliderUI;

/**
 * <p>
 * BasicSliderUI.java This is the UI delegate in the Basic look and feel that
 * paints JSliders.
 * </p>
 *
 * <p>
 * The UI delegate keeps track of 6 rectangles that place the various parts of
 * the JSlider inside the component.
 * </p>
 *
 * <p>
 * The rectangles are organized as follows:
 * </p>
 * <pre>
 *     +-------------------------------------------------------+ <-- focusRect
 *     |                                                       |
 *     |  +==+-------------------+==+--------------------+==+<------ contentRect
 *     |  |  |                   |  |<---thumbRect       |  |  |
 *     |  |  |    TRACK          |  |                    |<--------- trackRect
 *     |  |  +-------------------+==+--------------------+  |  |
 *     |  |  |                                           |  |  |
 *     |  |  |          TICKS GO HERE                    |<-------- tickRect
 *     |  |  |                                           |  |  |
 *     |  +==+-------------------------------------------+==+  |
 *     |  |  |                                           |  |  |
 *     |  |  |                                           |  |<----- labelRect
 *     |  |  |                 LABELS GO HERE            |  |  |
 *     |  |  |                                           |  |  |
 *     |  |  |                                           |  |  |
 *     |  |  |                                           |  |  |
 *     |  |  |                                           |  |  |
 *     |  |                                              |  |  |
 * </pre>
 *
 * <p>
 * The space between the contentRect and the focusRect are the FocusInsets.
 * </p>
 *
 * <p>
 * The space between the focusRect and the component bounds is the insetCache
 * which are the component's insets.
 * </p>
 *
 * <p>
 * The top of the thumb is the top of the contentRect. The trackRect has to be
 * as tall as the thumb.
 * </p>
 *
 * <p>
 * The trackRect and tickRect do not start from the left edge of the
 * focusRect. They are trackBuffer away from each side of the focusRect. This
 * is so that the thumb has room to move.
 * </p>
 *
 * <p>
 * The labelRect does start right against the contentRect's left and right
 * edges and it gets all remaining space.
 * </p>
 */
public class BasicSliderUI extends SliderUI
{
  /**
   * Helper class that listens to the {@link JSlider}'s model for changes.
   *
   * @specnote Apparently this class was intended to be protected,
   *           but was made public by a compiler bug and is now
   *           public for compatibility.
   */
  public class ChangeHandler implements ChangeListener
  {
    /**
     * Called when the slider's model has been altered. The UI delegate should
     * recalculate any rectangles that are dependent on the model for their
     * positions and repaint.
     *
     * @param e A static {@link ChangeEvent} passed from the model.
     */
    public void stateChanged(ChangeEvent e)
    {
      // Maximum, minimum, and extent values will be taken
      // care of automatically when the slider is repainted.
      // Only thing that needs recalculation is the thumb.
      calculateThumbLocation();
      slider.repaint();
    }
  }

  /**
   * Helper class that listens for resize events.
   *
   * @specnote Apparently this class was intended to be protected,
   *           but was made public by a compiler bug and is now
   *           public for compatibility.
   */
  public class ComponentHandler extends ComponentAdapter
  {
    /**
     * Called when the size of the component changes. The UI delegate should
     * recalculate any rectangles that are dependent on the model for their
     * positions and repaint.
     *
     * @param e A {@link ComponentEvent}.
     */
    public void componentResized(ComponentEvent e)
    {
      calculateGeometry();
      slider.repaint();
    }
  }

  /**
   * Helper class that listens for focus events.
   *
   * @specnote Apparently this class was intended to be protected,
   *           but was made public by a compiler bug and is now
   *           public for compatibility.
   */
  public class FocusHandler implements FocusListener
  {
    /**
     * Called when the {@link JSlider} has gained focus.  It should repaint
     * the slider with the focus drawn.
     *
     * @param e A {@link FocusEvent}.
     */
    public void focusGained(FocusEvent e)
    {
      slider.repaint();
    }

    /**
     * Called when the {@link JSlider} has lost focus. It  should repaint the
     * slider without the focus drawn.
     *
     * @param e A {@link FocusEvent}.
     */
    public void focusLost(FocusEvent e)
    {
      slider.repaint();
    }
  }

  /**
   * Helper class that listens for changes to the properties of the {@link
   * JSlider}.
   */
  public class PropertyChangeHandler implements PropertyChangeListener
  {
    /**
     * Called when one of the properties change. The UI should recalculate any
     * rectangles if necessary and repaint.
     *
     * @param e A {@link PropertyChangeEvent}.
     */
    public void propertyChange(PropertyChangeEvent e)
    {
      // Check for orientation changes.
      String prop = e.getPropertyName();
      if (prop.equals("orientation")
          || prop.equals("inverted")
          || prop.equals("labelTable")
          || prop.equals("majorTickSpacing")
          || prop.equals("minorTickSpacing")
          || prop.equals("paintTicks")
          || prop.equals("paintTrack")
          || prop.equals("paintLabels"))
        {
          calculateGeometry();
          slider.repaint();
        }
      else if (e.getPropertyName().equals("model"))
        {
          BoundedRangeModel oldModel = (BoundedRangeModel) e.getOldValue();
          oldModel.removeChangeListener(changeListener);
          slider.getModel().addChangeListener(changeListener);
          calculateThumbLocation();
          slider.repaint();
        }
    }
  }

  /**
   * Helper class that listens to our swing timer. This class is responsible
   * for listening to the timer and moving the thumb in the proper direction
   * every interval.
   *
   * @specnote Apparently this class was intended to be protected,
   *           but was made public by a compiler bug and is now
   *           public for compatibility.
   */
  public class ScrollListener implements ActionListener
  {
    /** Indicates which direction the thumb should scroll. */
    private transient int direction;

    /** Indicates whether we should scroll in blocks or in units. */
    private transient boolean block;

    /**
     * Creates a new ScrollListener object.
     */
    public ScrollListener()
    {
      direction = POSITIVE_SCROLL;
      block = false;
    }

    /**
     * Creates a new ScrollListener object.
     *
     * @param dir The direction to scroll in.
     * @param block If movement will be in blocks.
     */
    public ScrollListener(int dir, boolean block)
    {
      direction = dir;
      this.block = block;
    }

    /**
     * Called every time the swing timer reaches its interval. If the thumb
     * needs to move, then this method will move the thumb one block or  unit
     * in the direction desired. Otherwise, the timer can be stopped.
     *
     * @param e An {@link ActionEvent}.
     */
    public void actionPerformed(ActionEvent e)
    {
      if (! trackListener.shouldScroll(direction))
        {
          scrollTimer.stop();
          return;
        }

      if (block)
        scrollByBlock(direction);
      else
        scrollByUnit(direction);
    }

    /**
     * Sets the direction to scroll in.
     *
     * @param direction The direction to scroll in.
     */
    public void setDirection(int direction)
    {
      this.direction = direction;
    }

    /**
     * Sets whether movement will be in blocks.
     *
     * @param block If movement will be in blocks.
     */
    public void setScrollByBlock(boolean block)
    {
      this.block = block;
    }
  }

  /**
   * Helper class that listens for mouse events.
   *
   * @specnote Apparently this class was intended to be protected,
   *           but was made public by a compiler bug and is now
   *           public for compatibility.
   */
  public class TrackListener extends MouseInputAdapter
  {
    /** The current X position of the mouse. */
    protected int currentMouseX;

    /** The current Y position of the mouse. */
    protected int currentMouseY;

    /**
     * The offset between the current slider value and the cursor's position.
     */
    protected int offset;

    /**
     * Called when the mouse has been dragged. This should find the mouse's
     * current position and adjust the value of the {@link JSlider}
     * accordingly.
     *
     * @param e A {@link MouseEvent}
     */
    public void mouseDragged(MouseEvent e)
    {
      dragging = true;
      if (slider.isEnabled())
        {
          currentMouseX = e.getX();
          currentMouseY = e.getY();
          if (slider.getValueIsAdjusting())
            {
              int value;
              if (slider.getOrientation() == JSlider.HORIZONTAL)
                value = valueForXPosition(currentMouseX) - offset;
              else
                value = valueForYPosition(currentMouseY) - offset;

              slider.setValue(value);
            }
        }
    }

    /**
     * Called when the mouse has moved over a component but no buttons have
     * been pressed yet.
     *
     * @param e A {@link MouseEvent}
     */
    public void mouseMoved(MouseEvent e)
    {
      // Don't care that we're moved unless we're dragging.
    }

    /**
     * Called when the mouse is pressed. When the press occurs on the thumb
     * itself, the {@link JSlider} should have its value set to where the
     * mouse was pressed. If the press occurs on the track, then the thumb
     * should move one block towards the direction of the mouse.
     *
     * @param e A {@link MouseEvent}
     */
    public void mousePressed(MouseEvent e)
    {
      if (slider.isEnabled())
        {
          currentMouseX = e.getX();
          currentMouseY = e.getY();

          int value;
          if (slider.getOrientation() == JSlider.HORIZONTAL)
            value = valueForXPosition(currentMouseX);
          else
            value = valueForYPosition(currentMouseY);

          if (slider.getSnapToTicks())
            value = findClosestTick(value);

          // If the thumb is hit, then we don't need to set the timers to
          // move it.
          if (! thumbRect.contains(e.getPoint()))
            {
              // The mouse has hit some other part of the slider.
              // The value moves no matter where in the slider you hit.
              if (value > slider.getValue())
                scrollDueToClickInTrack(POSITIVE_SCROLL);
              else
                scrollDueToClickInTrack(NEGATIVE_SCROLL);
            }
          else
            {
              slider.setValueIsAdjusting(true);
              offset = value - slider.getValue();
            }
        }
    }

    /**
     * Called when the mouse is released.  This should stop the timer that
     * scrolls the thumb.
     *
     * @param e A {@link MouseEvent}
     */
    public void mouseReleased(MouseEvent e)
    {
      dragging = false;
      if (slider.isEnabled())
        {
          currentMouseX = e.getX();
          currentMouseY = e.getY();

          if (slider.getValueIsAdjusting())
            {
              slider.setValueIsAdjusting(false);
              if (slider.getSnapToTicks())
                slider.setValue(findClosestTick(slider.getValue()));
            }
          if (scrollTimer != null)
            scrollTimer.stop();
        }
      slider.repaint();
    }

    /**
     * Indicates whether the thumb should scroll in the given direction.
     *
     * @param direction The direction to check.
     *
     * @return True if the thumb should move in that direction.
     */
    public boolean shouldScroll(int direction)
    {
      int value;
      if (slider.getOrientation() == JSlider.HORIZONTAL)
        value = valueForXPosition(currentMouseX);
      else
        value = valueForYPosition(currentMouseY);

      if (direction == POSITIVE_SCROLL)
        return value > slider.getValue();
      else
        return value < slider.getValue();
    }
  }

  /**
   * This class is no longer used as of JDK1.3.
   */
  public class ActionScroller extends AbstractAction
  {
    /**
     * Not used.
     *
     * @param slider not used
     * @param dir not used
     * @param block not used
     */
    public ActionScroller(JSlider slider, int dir, boolean block)
    {
      // Not used.
    }

    /**
     * Not used.
     *
     * @param event not used
     */
    public void actionPerformed(ActionEvent event)
    {
      // Not used.
    }
  }

  /** Listener for changes from the model. */
  protected ChangeListener changeListener;

  /** Listener for changes to the {@link JSlider}. */
  protected PropertyChangeListener propertyChangeListener;

  /** Listener for the scrollTimer. */
  protected ScrollListener scrollListener;

  /** Listener for component resizing. */
  protected ComponentListener componentListener;

  /** Listener for focus handling. */
  protected FocusListener focusListener;

  /** Listener for mouse events. */
  protected TrackListener trackListener;

  /** The insets between the FocusRectangle and the ContentRectangle. */
  protected Insets focusInsets;

  /** The {@link JSlider}'s insets. */
  protected Insets insetCache;

  /** Rectangle describing content bounds. See diagram above. */
  protected Rectangle contentRect;

  /** Rectangle describing focus bounds. See diagram above. */
  protected Rectangle focusRect;

  /** Rectangle describing the thumb's bounds. See diagram above. */
  protected Rectangle thumbRect;

  /** Rectangle describing the tick bounds. See diagram above. */
  protected Rectangle tickRect;

  /** Rectangle describing the label bounds. See diagram above. */
  protected Rectangle labelRect;

  /** Rectangle describing the track bounds. See diagram above. */
  protected Rectangle trackRect;

  /** FIXME: use this somewhere. */
  public static final int MAX_SCROLL = 2;

  /** FIXME: use this somewhere. */
  public static final int MIN_SCROLL = -2;

  /** A constant describing scrolling towards the minimum. */
  public static final int NEGATIVE_SCROLL = -1;

  /** A constant describing scrolling towards the maximum. */
  public static final int POSITIVE_SCROLL = 1;

  /** The gap between the edges of the contentRect and trackRect. */
  protected int trackBuffer;

  /** Whether this slider is actually drawn left to right. */
  protected boolean leftToRightCache;

  /** A timer that periodically moves the thumb. */
  protected Timer scrollTimer;

  /** A reference to the {@link JSlider} that this UI was created for. */
  protected JSlider slider;

  /** The shadow color. */
  private transient Color shadowColor;

  /** The highlight color. */
  private transient Color highlightColor;

  /** The focus color. */
  private transient Color focusColor;

  /** True if the user is dragging the slider. */
  boolean dragging;

  /**
   * Creates a new Basic look and feel Slider UI.
   *
   * @param b The {@link JSlider} that this UI was created for.
   */
  public BasicSliderUI(JSlider b)
  {
    super();
  }

  /**
   * Returns true if the user is dragging the slider.
   *
   * @return true if the slider is being dragged.
   *
   * @since 1.5
   */
  protected boolean isDragging()
  {
    return dragging;
  }

  /**
   * Gets the shadow color to be used for this slider. The shadow color is the
   * color used for drawing the top and left edges of the track.
   *
   * @return The shadow color.
   */
  protected Color getShadowColor()
  {
    return shadowColor;
  }

  /**
   * Gets the highlight color to be used for this slider. The highlight color
   * is the color used for drawing the bottom and right edges of the track.
   *
   * @return The highlight color.
   */
  protected Color getHighlightColor()
  {
    return highlightColor;
  }

  /**
   * Gets the focus color to be used for this slider. The focus color is the
   * color used for drawing the focus rectangle when the component gains
   * focus.
   *
   * @return The focus color.
   */
  protected Color getFocusColor()
  {
    return focusColor;
  }

  /**
   * Factory method to create a BasicSliderUI for the given {@link
   * JComponent}, which should be a {@link JSlider}.
   *
   * @param b The {@link JComponent} a UI is being created for.
   *
   * @return A BasicSliderUI for the {@link JComponent}.
   */
  public static ComponentUI createUI(JComponent b)
  {
    return new BasicSliderUI((JSlider) b);
  }

  /**
   * Installs and initializes all fields for this UI delegate. Any properties
   * of the UI that need to be initialized and/or set to defaults will be
   * done now. It will also install any listeners necessary.
   *
   * @param c The {@link JComponent} that is having this UI installed.
   */
  public void installUI(JComponent c)
  {
    super.installUI(c);
    if (c instanceof JSlider)
      {
        slider = (JSlider) c;

        focusRect = new Rectangle();
        contentRect = new Rectangle();
        thumbRect = new Rectangle();
        trackRect = new Rectangle();
        tickRect = new Rectangle();
        labelRect = new Rectangle();

        insetCache = slider.getInsets();
        leftToRightCache = ! slider.getInverted();

        scrollTimer = new Timer(200, null);
        scrollTimer.setRepeats(true);

        installDefaults(slider);
        installListeners(slider);
        installKeyboardActions(slider);

        calculateFocusRect();

        calculateContentRect();
        calculateThumbSize();
        calculateTrackBuffer();
        calculateTrackRect();
        calculateThumbLocation();

        calculateTickRect();
        calculateLabelRect();
      }
  }

  /**
   * Performs the opposite of installUI. Any properties or resources that need
   * to be cleaned up will be done now. It will also uninstall any listeners
   * it has. In addition, any properties of this UI will be nulled.
   *
   * @param c The {@link JComponent} that is having this UI uninstalled.
   */
  public void uninstallUI(JComponent c)
  {
    super.uninstallUI(c);

    uninstallKeyboardActions(slider);
    uninstallListeners(slider);

    scrollTimer = null;

    focusRect = null;
    contentRect = null;
    thumbRect = null;
    trackRect = null;
    tickRect = null;
    labelRect = null;

    focusInsets = null;
  }

  /**
   * Initializes any default properties that this UI has from the defaults for
   * the Basic look and feel.
   *
   * @param slider The {@link JSlider} that is having this UI installed.
   */
  protected void installDefaults(JSlider slider)
  {
    LookAndFeel.installColors(slider, "Slider.background",
                              "Slider.foreground");
    LookAndFeel.installBorder(slider, "Slider.border");
    shadowColor = UIManager.getColor("Slider.shadow");
    highlightColor = UIManager.getColor("Slider.highlight");
    focusColor = UIManager.getColor("Slider.focus");
    focusInsets = UIManager.getInsets("Slider.focusInsets");
    slider.setOpaque(true);
  }

  /**
   * Creates a new {@link TrackListener}.
   *
   * @param slider The {@link JSlider} that this {@link TrackListener} is
   *        created for.
   *
   * @return A new {@link TrackListener}.
   */
  protected TrackListener createTrackListener(JSlider slider)
  {
    return new TrackListener();
  }

  /**
   * Creates a new {@link ChangeListener}.
   *
   * @param slider The {@link JSlider} that this {@link ChangeListener} is
   *        created for.
   *
   * @return A new {@link ChangeListener}.
   */
  protected ChangeListener createChangeListener(JSlider slider)
  {
    return new ChangeHandler();
  }

  /**
   * Creates a new {@link ComponentListener}.
   *
   * @param slider The {@link JSlider} that this {@link ComponentListener} is
   *        created for.
   *
   * @return A new {@link ComponentListener}.
   */
  protected ComponentListener createComponentListener(JSlider slider)
  {
    return new ComponentHandler();
  }

  /**
   * Creates a new {@link FocusListener}.
   *
   * @param slider The {@link JSlider} that this {@link FocusListener} is
   *        created for.
   *
   * @return A new {@link FocusListener}.
   */
  protected FocusListener createFocusListener(JSlider slider)
  {
    return new FocusHandler();
  }

  /**
   * Creates a new {@link ScrollListener}.
   *
   * @param slider The {@link JSlider} that this {@link ScrollListener} is
   *        created for.
   *
   * @return A new {@link ScrollListener}.
   */
  protected ScrollListener createScrollListener(JSlider slider)
  {
    return new ScrollListener();
  }

  /**
   * Creates a new {@link PropertyChangeListener}.
   *
   * @param slider The {@link JSlider} that this {@link
   *        PropertyChangeListener} is created for.
   *
   * @return A new {@link PropertyChangeListener}.
   */
  protected PropertyChangeListener createPropertyChangeListener(JSlider slider)
  {
    return new PropertyChangeHandler();
  }

  /**
   * Creates and registers all the listeners for this UI delegate. This
   * includes creating the ScrollListener and registering it to the timer.
   *
   * @param slider The {@link JSlider} is having listeners installed.
   */
  protected void installListeners(JSlider slider)
  {
    propertyChangeListener = createPropertyChangeListener(slider);
    componentListener = createComponentListener(slider);
    trackListener = createTrackListener(slider);
    focusListener = createFocusListener(slider);
    changeListener = createChangeListener(slider);
    scrollListener = createScrollListener(slider);

    slider.addPropertyChangeListener(propertyChangeListener);
    slider.addComponentListener(componentListener);
    slider.addMouseListener(trackListener);
    slider.addMouseMotionListener(trackListener);
    slider.addFocusListener(focusListener);
    slider.getModel().addChangeListener(changeListener);

    scrollTimer.addActionListener(scrollListener);
  }

  /**
   * Unregisters all the listeners that this UI delegate was using. In
   * addition, it will also null any listeners that it was using.
   *
   * @param slider The {@link JSlider} that is having listeners removed.
   */
  protected void uninstallListeners(JSlider slider)
  {
    slider.removePropertyChangeListener(propertyChangeListener);
    slider.removeComponentListener(componentListener);
    slider.removeMouseListener(trackListener);
    slider.removeMouseMotionListener(trackListener);
    slider.removeFocusListener(focusListener);
    slider.getModel().removeChangeListener(changeListener);

    scrollTimer.removeActionListener(scrollListener);

    propertyChangeListener = null;
    componentListener = null;
    trackListener = null;
    focusListener = null;
    changeListener = null;
    scrollListener = null;
  }

  /**
   * Installs any keyboard actions. The list of keys that need to be bound are
   * listed in Basic look and feel's defaults.
   *
   * @param slider The {@link JSlider} that is having keyboard actions
   *        installed.
   */
  protected void installKeyboardActions(JSlider slider)
  {
    InputMap keyMap = getInputMap(JComponent.WHEN_FOCUSED);
    SwingUtilities.replaceUIInputMap(slider, JComponent.WHEN_FOCUSED, keyMap);
    ActionMap map = getActionMap();
    SwingUtilities.replaceUIActionMap(slider, map);
  }

  /**
   * Uninstalls any keyboard actions. The list of keys used  are listed in
   * Basic look and feel's defaults.
   *
   * @param slider The {@link JSlider} that is having keyboard actions
   *        uninstalled.
   */
  protected void uninstallKeyboardActions(JSlider slider)
  {
    SwingUtilities.replaceUIActionMap(slider, null);
    SwingUtilities.replaceUIInputMap(slider, JComponent.WHEN_FOCUSED, null);
  }

  /* XXX: This is all after experimentation with SUN's implementation.

     PreferredHorizontalSize seems to be 200x21.
     PreferredVerticalSize seems to be 21x200.

     MinimumHorizontalSize seems to be 36x21.
     MinimumVerticalSize seems to be 21x36.

     PreferredSize seems to be 200x63. Or Components.getBounds?

     MinimumSize seems to be 36x63.

     MaximumSize seems to be 32767x63.
   */

  /**
   * This method returns the preferred size when the slider is horizontally
   * oriented.
   *
   * @return The dimensions of the preferred horizontal size.
   */
  public Dimension getPreferredHorizontalSize()
  {
    Dimension dim = UIManager.getDimension("Slider.horizontalSize");
    if (dim == null) // Just to be sure we mirror the default.
      dim = new Dimension(200, 21);
    return dim;
  }

  /**
   * This method returns the preferred size when the slider is vertically
   * oriented.
   *
   * @return The dimensions of the preferred vertical size.
   */
  public Dimension getPreferredVerticalSize()
  {
    Dimension dim = UIManager.getDimension("Slider.verticalSize");
    if (dim == null) // Just to be sure we mirror the default.
      dim = new Dimension(21, 200);
    return dim;
  }

  /**
   * This method returns the minimum size when the slider is horizontally
   * oriented.
   *
   * @return The dimensions of the minimum horizontal size.
   */
  public Dimension getMinimumHorizontalSize()
  {
    Dimension dim = UIManager.getDimension("Slider.minimumHorizontalSize");
    if (dim == null) // Just to be sure we mirror the default.
      dim = new Dimension(36, 21);
    return dim;
  }

  /**
   * This method returns the minimum size of the slider when it  is vertically
   * oriented.
   *
   * @return The dimensions of the minimum vertical size.
   */
  public Dimension getMinimumVerticalSize()
  {
    Dimension dim = UIManager.getDimension("Slider.minimumVerticalSize");
    if (dim == null) // Just to be sure we mirror the default.
      dim = new Dimension(21, 36);
    return dim;
  }

  /**
   * This method returns the preferred size of the component. If it returns
   * null, then it is up to the Layout Manager to give the {@link JComponent}
   * a size.
   *
   * @param c The {@link JComponent} to find the preferred size for.
   *
   * @return The dimensions of the preferred size.
   */
  public Dimension getPreferredSize(JComponent c)
  {
    recalculateIfInsetsChanged();
    Dimension dim;
    if (slider.getOrientation() == JSlider.HORIZONTAL)
      {
        // Create copy here to protect the UIManager value.
        dim = new Dimension(getPreferredHorizontalSize());
        dim.height = insetCache.top + insetCache.bottom;
        dim.height += focusInsets.top + focusInsets.bottom;
        dim.height += trackRect.height + tickRect.height + labelRect.height;
      }
    else
      {
        // Create copy here to protect the UIManager value.
        dim = new Dimension(getPreferredVerticalSize());
        dim.width = insetCache.left + insetCache.right;
        dim.width += focusInsets.left + focusInsets.right;
        dim.width += trackRect.width + tickRect.width + labelRect.width;
      }
    return dim;
  }

  /**
   * This method returns the minimum size for this {@link JSlider}  for this
   * look and feel. If it returns null, then it is up to the Layout Manager
   * to give the {@link JComponent} a size.
   *
   * @param c The {@link JComponent} to find the minimum size for.
   *
   * @return The dimensions of the minimum size.
   */
  public Dimension getMinimumSize(JComponent c)
  {
    recalculateIfInsetsChanged();
    Dimension dim;
    if (slider.getOrientation() == JSlider.HORIZONTAL)
      {
        // Create copy here to protect the UIManager value.
        dim = new Dimension(getMinimumHorizontalSize());
        dim.height = insetCache.top + insetCache.bottom;
        dim.height += focusInsets.top + focusInsets.bottom;
        dim.height += trackRect.height + tickRect.height + labelRect.height;
      }
    else
      {
        // Create copy here to protect the UIManager value.
        dim = new Dimension(getMinimumVerticalSize());
        dim.width = insetCache.left + insetCache.right;
        dim.width += focusInsets.left + focusInsets.right;
        dim.width += trackRect.width + tickRect.width + labelRect.width;
      }
    return dim;
  }

  /**
   * This method returns the maximum size for this {@link JSlider} for this
   * look and feel.
   *
   * @param c The {@link JComponent} to find a maximum size for.
   *
   * @return The dimensions of the maximum size.
   */
  public Dimension getMaximumSize(JComponent c)
  {
    Dimension dim = getPreferredSize(c);
    if (slider.getOrientation() == JSlider.HORIZONTAL)
      dim.width = Short.MAX_VALUE;
    else
      dim.height = Short.MAX_VALUE;
    return dim;
  }

  /**
   * This method calculates all the sizes of the rectangles by delegating to
   * the helper methods calculateXXXRect.
   */
  protected void calculateGeometry()
  {
    calculateFocusRect();
    calculateContentRect();
    calculateThumbSize();
    calculateTrackBuffer();
    calculateTrackRect();
    calculateTickRect();
    calculateLabelRect();
    calculateThumbLocation();
  }

  /**
   * This method calculates the size and position of the focusRect. This
   * method does not need to be called if the orientation changes.
   */
  protected void calculateFocusRect()
  {
    focusRect.x = insetCache.left;
    focusRect.y = insetCache.top;
    focusRect.width = slider.getWidth() - insetCache.left - insetCache.right;
    focusRect.height = slider.getHeight() - insetCache.top - insetCache.bottom;
  }

  /**
   * Sets the width and height of the <code>thumbRect</code> field, using the
   * dimensions returned by {@link #getThumbSize()}.
   */
  protected void calculateThumbSize()
  {
    Dimension d = getThumbSize();
    thumbRect.width = d.width;
    thumbRect.height = d.height;
  }

  /**
   * Updates the <code>contentRect</code> field to an area inside the
   * <code>focusRect</code>. This method does not need to be called if the
   * orientation changes.
   */
  protected void calculateContentRect()
  {
    contentRect.x = focusRect.x + focusInsets.left;
    contentRect.y = focusRect.y + focusInsets.top;

    contentRect.width = focusRect.width - focusInsets.left - focusInsets.right;
    contentRect.height = focusRect.height - focusInsets.top
                         - focusInsets.bottom;
  }

  /**
   * Calculates the position of the thumbRect based on the current value of
   * the slider. It must take into  account the orientation of the slider.
   */
  protected void calculateThumbLocation()
  {
    int value = slider.getValue();

    if (slider.getOrientation() == JSlider.HORIZONTAL)
      {
        thumbRect.x = xPositionForValue(value) - thumbRect.width / 2;
        thumbRect.y = trackRect.y + 1;
      }
    else
      {
        thumbRect.x = trackRect.x + 1;
        thumbRect.y = yPositionForValue(value) - thumbRect.height / 2;
      }
  }

  /**
   * Calculates the gap size between the edge of the <code>contentRect</code>
   * and the edge of the <code>trackRect</code>, storing the result in the
   * <code>trackBuffer</code> field.  Sufficient space needs to be reserved
   * for the slider thumb and/or the labels at each end of the slider track.
   */
  protected void calculateTrackBuffer()
  {
    if (slider.getOrientation() == JSlider.HORIZONTAL)
      {
        int w = Math.max(getWidthOfLowValueLabel(), getWidthOfHighValueLabel());
        trackBuffer = Math.max(thumbRect.width / 2, w / 2);

      }
    else
      {
        int h = Math.max(getHeightOfLowValueLabel(),
                         getHeightOfHighValueLabel());
        trackBuffer = Math.max(thumbRect.height / 2, h / 2);
      }
  }

  /**
   * Returns the size of the slider's thumb.  The size is hard coded to
   * <code>11 x 20</code> for horizontal sliders, and <code>20 x 11</code> for
   * vertical sliders. Note that a new instance of {@link Dimension} is
   * returned for every call to this method (this seems wasteful, but
   * {@link Dimension} instances are not immutable, so this is probably
   * unavoidable).
   *
   * @return The size of the slider's thumb.
   */
  protected Dimension getThumbSize()
  {
    if (slider.getOrientation() == JSlider.HORIZONTAL)
      return new Dimension(11, 20);
    else
      return new Dimension(20, 11);
  }

  /**
   * Calculates the size and position of the trackRect. It must take into
   * account the orientation of the slider.
   */
  protected void calculateTrackRect()
  {
    if (slider.getOrientation() == JSlider.HORIZONTAL)
      {
        int center = thumbRect.height;
        if (slider.getPaintTicks())
          center += getTickLength();
        if (slider.getPaintLabels())
          center += getHeightOfTallestLabel();
        trackRect.x = contentRect.x + trackBuffer;
        trackRect.y = contentRect.y + (contentRect.height - center - 1) / 2;
        trackRect.width = contentRect.width - 2 * trackBuffer;
        trackRect.height = thumbRect.height;
      }
    else
      {
        int center = thumbRect.width;
        if (slider.getPaintTicks())
          center += getTickLength();
        if (slider.getPaintLabels())
          center += getWidthOfWidestLabel();
        trackRect.x = contentRect.x + (contentRect.width - center - 1) / 2;
        trackRect.y = contentRect.y + trackBuffer;
        trackRect.width = thumbRect.width;
        trackRect.height = contentRect.height - 2 * trackBuffer;
      }
  }

  /**
   * This method returns the height of the tick area box if the slider  is
   * horizontal and the width of the tick area box is the slider is vertical.
   * It not necessarily how long the ticks will be. If a gap between the edge
   * of tick box and the actual tick is desired, then that will need to be
   * handled in the tick painting methods.
   *
   * @return The height (or width if the slider is vertical) of the tick
   *         rectangle.
   */
  protected int getTickLength()
  {
    return 8;
  }

  /**
   * This method calculates the size and position of the tickRect. It must
   * take into account the orientation of the slider.
   */
  protected void calculateTickRect()
  {
    if (slider.getOrientation() == JSlider.HORIZONTAL)
      {
        tickRect.x = trackRect.x;
        tickRect.y = trackRect.y + trackRect.height;
        tickRect.width = trackRect.width;
        tickRect.height = getTickLength();

        // this makes our Mauve tests pass...can't explain it!
        if (!slider.getPaintTicks())
          {
            tickRect.y--;
            tickRect.height = 0;
          }
      }
    else
      {
        tickRect.x = trackRect.x + trackRect.width;
        tickRect.y = trackRect.y;
        tickRect.width = getTickLength();
        tickRect.height = trackRect.height;

        // this makes our Mauve tests pass...can't explain it!
        if (!slider.getPaintTicks())
          {
            tickRect.x--;
            tickRect.width = 0;
          }
      }
  }

  /**
   * Calculates the <code>labelRect</code> field, taking into account the
   * orientation of the slider.
   */
  protected void calculateLabelRect()
  {
    if (slider.getOrientation() == JSlider.HORIZONTAL)
      {
        if (slider.getPaintLabels())
          {
            labelRect.x = tickRect.x - trackBuffer;
            labelRect.y = tickRect.y + tickRect.height;
            labelRect.width = tickRect.width + trackBuffer * 2;
            labelRect.height = getHeightOfTallestLabel();
          }
        else
          {
            labelRect.x = tickRect.x;
            labelRect.y = tickRect.y + tickRect.height;
            labelRect.width = tickRect.width;
            labelRect.height = 0;
          }
      }
    else
      {
        if (slider.getPaintLabels())
          {
            labelRect.x = tickRect.x + tickRect.width;
            labelRect.y = tickRect.y - trackBuffer;
            labelRect.width = getWidthOfWidestLabel();
            labelRect.height = tickRect.height + trackBuffer * 2;
          }
        else
          {
            labelRect.x = tickRect.x + tickRect.width;
            labelRect.y = tickRect.y;
            labelRect.width = 0;
            labelRect.height = tickRect.height;
          }
      }
  }

  /**
   * This method returns the width of the widest label  in the slider's label
   * table.
   *
   * @return The width of the widest label or 0 if no label table exists.
   */
  protected int getWidthOfWidestLabel()
  {
    int widest = 0;
    Dictionary table = slider.getLabelTable();
    if (table != null)
      {
        for (Enumeration list = slider.getLabelTable().elements();
             list.hasMoreElements();)
          {
            Component label = (Component) list.nextElement();
            widest = Math.max(label.getPreferredSize().width, widest);
          }
      }
    return widest;
  }

  /**
   * This method returns the height of the tallest label in the slider's label
   * table.
   *
   * @return The height of the tallest label or 0 if no label table exists.
   */
  protected int getHeightOfTallestLabel()
  {
    int tallest = 0;
    Component label;

    if (slider.getLabelTable() == null)
      return 0;
    Dimension pref;
    for (Enumeration list = slider.getLabelTable().elements();
         list.hasMoreElements();)
      {
        Object comp = list.nextElement();
        if (! (comp instanceof Component))
          continue;
        label = (Component) comp;
        pref = label.getPreferredSize();
        if (pref != null && pref.height > tallest)
          tallest = pref.height;
      }
    return tallest;
  }

  /**
   * Returns the width of the label whose key has the highest value, or 0 if
   * there are no labels.
   *
   * @return The width of the label whose key has the highest value.
   *
   * @see #getHighestValueLabel()
   */
  protected int getWidthOfHighValueLabel()
  {
    Component highValueLabel = getHighestValueLabel();
    if (highValueLabel != null)
      return highValueLabel.getPreferredSize().width;
    else
      return 0;
  }

  /**
   * Returns the width of the label whose key has the lowest value, or 0 if
   * there are no labels.
   *
   * @return The width of the label whose key has the lowest value.
   *
   * @see #getLowestValueLabel()
   */
  protected int getWidthOfLowValueLabel()
  {
    Component lowValueLabel = getLowestValueLabel();
    if (lowValueLabel != null)
      return lowValueLabel.getPreferredSize().width;
    else
      return 0;
  }

  /**
   * Returns the height of the label whose key has the highest value, or 0 if
   * there are no labels.
   *
   * @return The height of the high value label or 0 if no label table exists.
   */
  protected int getHeightOfHighValueLabel()
  {
    Component highValueLabel = getHighestValueLabel();
    if (highValueLabel != null)
      return highValueLabel.getPreferredSize().height;
    else
      return 0;
  }

  /**
   * Returns the height of the label whose key has the lowest value, or 0 if
   * there are no labels.
   *
   * @return The height of the low value label or 0 if no label table exists.
   */
  protected int getHeightOfLowValueLabel()
  {
    Component lowValueLabel = getLowestValueLabel();
    if (lowValueLabel != null)
      return lowValueLabel.getPreferredSize().height;
    else
      return 0;
  }

  /**
   * Returns <code>true</code> if the slider scale is to be drawn inverted,
   * and <code>false</code> if not.
   *
   * @return <code>true</code> if the slider is to be drawn inverted.
   */
  protected boolean drawInverted()
  {
    return slider.getInverted();
  }

  /**
   * This method returns the label whose key has the lowest value.
   *
   * @return The low value label or null if no label table exists.
   */
  protected Component getLowestValueLabel()
  {
    Integer key = new Integer(Integer.MAX_VALUE);
    Integer tmpKey;
    Dictionary labelTable = slider.getLabelTable();

    if (labelTable == null)
      return null;

    for (Enumeration list = labelTable.keys(); list.hasMoreElements();)
      {
        Object value = list.nextElement();
        if (! (value instanceof Integer))
          continue;
        tmpKey = (Integer) value;
        if (tmpKey.intValue() < key.intValue())
          key = tmpKey;
      }
    Object comp = labelTable.get(key);
    if (! (comp instanceof Component))
      return null;
    return (Component) comp;
  }

  /**
   * Returns the label whose key has the highest value.
   *
   * @return The label whose key has the highest value or <code>null</code> if
   *     no label table exists.
   */
  protected Component getHighestValueLabel()
  {
    Integer key = new Integer(Integer.MIN_VALUE);
    Integer tmpKey;
    Dictionary labelTable = slider.getLabelTable();

    if (labelTable == null)
      return null;

    for (Enumeration list = labelTable.keys(); list.hasMoreElements();)
      {
        Object value = list.nextElement();
        if (! (value instanceof Integer))
          continue;
        tmpKey = (Integer) value;
        if (tmpKey.intValue() > key.intValue())
          key = tmpKey;
      }
    Object comp = labelTable.get(key);
    if (! (comp instanceof Component))
      return null;
    return (Component) comp;
  }

  /**
   * This method is used to paint the {@link JSlider}. It delegates all its
   * duties to the various paint methods like paintTicks(),  paintTrack(),
   * paintThumb(), etc.
   *
   * @param g The {@link Graphics} object to paint with.
   * @param c The {@link JComponent} that is being painted.
   */
  public void paint(Graphics g, JComponent c)
  {
    recalculateIfInsetsChanged();
    recalculateIfOrientationChanged();
    if (slider.getPaintTrack() && hitClip(g, trackRect))
      paintTrack(g);
    if (slider.getPaintTicks() && hitClip(g, tickRect))
      paintTicks(g);
    if (slider.getPaintLabels() && hitClip(g, labelRect))
      paintLabels(g);
    if (slider.hasFocus() && hitClip(g, focusRect))
      paintFocus(g);
    if (hitClip(g, thumbRect))
      paintThumb(g);
  }

  /**
   * This method recalculates any rectangles that need to be recalculated
   * after the insets of the component have changed.
   */
  protected void recalculateIfInsetsChanged()
  {
    Insets insets = slider.getInsets();
    if (! insets.equals(insetCache))
      {
        insetCache = insets;
        calculateGeometry();
      }
  }

  /**
   * This method recalculates any rectangles that need to be recalculated
   * after the orientation of the slider changes.
   */
  protected void recalculateIfOrientationChanged()
  {
    // Examining a test program shows that either Sun calls private
    // methods that we don't know about, or these don't do anything.
    calculateThumbSize();
    calculateTrackBuffer();
    calculateTrackRect();
    calculateThumbLocation();

    calculateTickRect();
    calculateLabelRect();
  }

  /**
   * This method is called during a repaint if the slider has focus. It draws
   * an outline of the  focusRect using the color returned by
   * getFocusColor().
   *
   * @param g The {@link Graphics} object to draw with.
   */
  public void paintFocus(Graphics g)
  {
    Color saved_color = g.getColor();

    g.setColor(getFocusColor());

    g.drawRect(focusRect.x, focusRect.y, focusRect.width, focusRect.height);

    g.setColor(saved_color);
  }

  /**
   * <p>
   * This method is called during a repaint if the  track is to be drawn. It
   * draws a 3D rectangle to  represent the track. The track is not the size
   * of the trackRect. The top and left edges of the track should be outlined
   * with the shadow color. The bottom and right edges should be outlined
   * with the highlight color.
   * </p>
   * <pre>
   *    a---d
   *    |   |
   *    |   |   a------------------------d
   *    |   |   |                        |
   *    |   |   b------------------------c
   *    |   |
   *    |   |
   *    b---c
   * </pre>
   *
   * <p>
   * The b-a-d path needs to be drawn with the shadow color and the b-c-d path
   * needs to be drawn with the highlight color.
   * </p>
   *
   * @param g The {@link Graphics} object to draw with.
   */
  public void paintTrack(Graphics g)
  {
    Color saved_color = g.getColor();
    int width;
    int height;

    Point a = new Point(trackRect.x, trackRect.y + 1);
    Point b = new Point(a);
    Point c = new Point(a);
    Point d = new Point(a);

    if (slider.getOrientation() == JSlider.HORIZONTAL)
      {
        width = trackRect.width;
        height = (thumbRect.height / 4 == 0) ? 1 : thumbRect.height / 4;

        a.translate(0, (trackRect.height / 2) - (height / 2));
        b.translate(0, (trackRect.height / 2) + (height / 2));
        c.translate(trackRect.width, (trackRect.height / 2) + (height / 2));
        d.translate(trackRect.width, (trackRect.height / 2) - (height / 2));
      }
    else
      {
        width = (thumbRect.width / 4 == 0) ? 1 : thumbRect.width / 4;
        height = trackRect.height;

        a.translate((trackRect.width / 2) - (width / 2), 0);
        b.translate((trackRect.width / 2) - (width / 2), trackRect.height);
        c.translate((trackRect.width / 2) + (width / 2), trackRect.height);
        d.translate((trackRect.width / 2) + (width / 2), 0);
      }
    g.setColor(Color.GRAY);
    g.fillRect(a.x, a.y, width, height);

    g.setColor(getHighlightColor());
    g.drawLine(b.x, b.y, c.x, c.y);
    g.drawLine(c.x, c.y, d.x, d.y);

    g.setColor(getShadowColor());
    g.drawLine(b.x, b.y, a.x, a.y);
    g.drawLine(a.x, a.y, d.x, d.y);

    g.setColor(saved_color);
  }

  /**
   * This method is called during a repaint if the ticks are to be drawn. This
   * method must still verify that the majorTickSpacing and minorTickSpacing
   * are greater than zero before drawing the ticks.
   *
   * @param g The {@link Graphics} object to draw with.
   */
  public void paintTicks(Graphics g)
  {
    int max = slider.getMaximum();
    int min = slider.getMinimum();
    int majorSpace = slider.getMajorTickSpacing();
    int minorSpace = slider.getMinorTickSpacing();

    if (majorSpace > 0)
      {
        if (slider.getOrientation() == JSlider.HORIZONTAL)
          {
            g.translate(0, tickRect.y);
            for (int i = min; i <= max; i += majorSpace)
              paintMajorTickForHorizSlider(g, tickRect, xPositionForValue(i));
            g.translate(0, -tickRect.y);
          }
        else // JSlider.VERTICAL
          {
            g.translate(tickRect.x, 0);
            for (int i = min; i <= max; i += majorSpace)
              paintMajorTickForVertSlider(g, tickRect, yPositionForValue(i));
            g.translate(-tickRect.x, 0);
          }
      }
    if (minorSpace > 0)
      {
        if (slider.getOrientation() == JSlider.HORIZONTAL)
          {
            g.translate(0, tickRect.y);
            for (int i = min; i <= max; i += minorSpace)
              paintMinorTickForHorizSlider(g, tickRect, xPositionForValue(i));
            g.translate(0, -tickRect.y);
          }
        else
          {
            g.translate(tickRect.x, 0);
            for (int i = min; i <= max; i += minorSpace)
              paintMinorTickForVertSlider(g, tickRect, yPositionForValue(i));
            g.translate(-tickRect.x, 0);
          }
      }
  }

  /* Minor ticks start at 1/4 of the height (or width) of the tickRect and
     extend to 1/2 of the tickRect.

     Major ticks start at 1/4 of the height and extend to 3/4.
   */

  /**
   * This method paints a minor tick for a horizontal slider at the given x
   * value. x represents the x coordinate to paint at.
   *
   * @param g The {@link Graphics} object to draw with.
   * @param tickBounds The tickRect rectangle.
   * @param x The x coordinate to draw the tick at.
   */
  protected void paintMinorTickForHorizSlider(Graphics g,
                                              Rectangle tickBounds, int x)
  {
    int y = tickRect.height / 4;
    Color saved = g.getColor();
    g.setColor(Color.BLACK);

    g.drawLine(x, y, x, y + tickRect.height / 4);
    g.setColor(saved);
  }

  /**
   * This method paints a major tick for a horizontal slider at the given x
   * value. x represents the x coordinate to paint at.
   *
   * @param g The {@link Graphics} object to draw with.
   * @param tickBounds The tickRect rectangle.
   * @param x The x coordinate to draw the tick at.
   */
  protected void paintMajorTickForHorizSlider(Graphics g,
                                              Rectangle tickBounds, int x)
  {
    int y = tickRect.height / 4;
    Color saved = g.getColor();
    g.setColor(Color.BLACK);

    g.drawLine(x, y, x, y + tickRect.height / 2);
    g.setColor(saved);
  }

  /**
   * This method paints a minor tick for a vertical slider at the given y
   * value. y represents the y coordinate to paint at.
   *
   * @param g The {@link Graphics} object to draw with.
   * @param tickBounds The tickRect rectangle.
   * @param y The y coordinate to draw the tick at.
   */
  protected void paintMinorTickForVertSlider(Graphics g, Rectangle tickBounds,
                                             int y)
  {
    int x = tickRect.width / 4;
    Color saved = g.getColor();
    g.setColor(Color.BLACK);

    g.drawLine(x, y, x + tickRect.width / 4, y);
    g.setColor(saved);
  }

  /**
   * This method paints a major tick for a vertical slider at the given y
   * value. y represents the y coordinate to paint at.
   *
   * @param g The {@link Graphics} object to draw with.
   * @param tickBounds The tickRect rectangle.
   * @param y The y coordinate to draw the tick at.
   */
  protected void paintMajorTickForVertSlider(Graphics g, Rectangle tickBounds,
                                             int y)
  {
    int x = tickRect.width / 4;
    Color saved = g.getColor();
    g.setColor(Color.BLACK);

    g.drawLine(x, y, x + tickRect.width / 2, y);
    g.setColor(saved);
  }

  /**
   * This method paints all the labels from the slider's label table. This
   * method must make sure that the label table is not null before painting
   * the labels. Each entry in the label table is a (integer, component)
   * pair. Every label is painted at the value of the integer.
   *
   * @param g The {@link Graphics} object to draw with.
   */
  public void paintLabels(Graphics g)
  {
    Dictionary table = slider.getLabelTable();
    if (table != null)
      {
        int min = slider.getMinimum();
        int max = slider.getMaximum();
        for (Enumeration list = table.keys(); list.hasMoreElements();)
          {
            Integer key = (Integer) list.nextElement();
            int value = key.intValue();
            if (value >= min && value <= max)
              {
                Component label = (Component) table.get(key);
                if (slider.getOrientation() == JSlider.HORIZONTAL)
                  {
                    g.translate(0, labelRect.y);
                    paintHorizontalLabel(g, value, label);
                    g.translate(0, -labelRect.y);
                  }
                else
                  {
                    g.translate(labelRect.x, 0);
                    paintVerticalLabel(g, value, label);
                    g.translate(-labelRect.x, 0);
                  }
              }
          }
      }
  }

  /**
   * This method paints the label on the horizontal slider at the value
   * specified. The value is not a coordinate. It is a value within the range
   * of the  slider. If the value is not within the range of the slider, this
   * method will do nothing. This method should not paint outside the
   * boundaries of the labelRect.
   *
   * @param g The {@link Graphics} object to draw with.
   * @param value The value to paint at.
   * @param label The label to paint.
   */
  protected void paintHorizontalLabel(Graphics g, int value, Component label)
  {
    int center = xPositionForValue(value);
    int left = center - label.getPreferredSize().width / 2;
    g.translate(left, 0);
    label.paint(g);
    g.translate(-left, 0);
  }

  /**
   * This method paints the label on the vertical slider at the value
   * specified. The value is not a coordinate. It is a value within the range
   * of the  slider. If the value is not within the range of the slider, this
   * method will do nothing. This method should not paint outside the
   * boundaries of the labelRect.
   *
   * @param g The {@link Graphics} object to draw with.
   * @param value The value to paint at.
   * @param label The label to paint.
   */
  protected void paintVerticalLabel(Graphics g, int value, Component label)
  {
    int center = yPositionForValue(value);
    int top = center - label.getPreferredSize().height / 2;
    g.translate(0, top);
    label.paint(g);
    g.translate(0, -top);
  }

  /**
   * <p>
   * This method paints a thumb. There are two types of thumb:
   * </p>
   * <pre>
   *   Vertical         Horizontal
   *    a---b            a-----b
   *    |   |            |      \
   *    e   c            |       c
   *     \ /             |      /
   *      d              e-----d
   *  </pre>
   *
   * <p>
   * In the case of vertical thumbs, we highlight the path b-a-e-d and shadow
   * the path b-c-d. In the case of horizontal thumbs, we highlight the path
   * c-b-a-e and shadow the path c-d-e. In both cases we fill the path
   * a-b-c-d-e before shadows and highlights are drawn.
   * </p>
   *
   * @param g The graphics object to paint with
   */
  public void paintThumb(Graphics g)
  {
    Color saved_color = g.getColor();

    Point a = new Point(thumbRect.x, thumbRect.y);
    Point b = new Point(a);
    Point c = new Point(a);
    Point d = new Point(a);
    Point e = new Point(a);

    Polygon bright;
    Polygon light; // light shadow
    Polygon dark; // dark shadow
    Polygon all;

    // This will be in X-dimension if the slider is inverted and y if it isn't.
    int turnPoint;

    if (slider.getOrientation() == JSlider.HORIZONTAL)
      {
        turnPoint = thumbRect.height * 3 / 4;

        b.translate(thumbRect.width - 1, 0);
        c.translate(thumbRect.width - 1, turnPoint);
        d.translate(thumbRect.width / 2 - 1, thumbRect.height - 1);
        e.translate(0, turnPoint);

        bright = new Polygon(new int[] { b.x - 1, a.x, e.x, d.x },
                             new int[] { b.y, a.y, e.y, d.y }, 4);

        dark = new Polygon(new int[] { b.x, c.x, d.x + 1 }, new int[] { b.y,
                                                                       c.y - 1,
                                                                       d.y }, 3);

        light = new Polygon(new int[] { b.x - 1, c.x - 1, d.x + 1 },
                            new int[] { b.y + 1, c.y - 1, d.y - 1 }, 3);

        all = new Polygon(
                          new int[] { a.x + 1, b.x - 2, c.x - 2, d.x, e.x + 1 },
                          new int[] { a.y + 1, b.y + 1, c.y - 1, d.y - 1, e.y },
                          5);
      }
    else
      {
        turnPoint = thumbRect.width * 3 / 4 - 1;

        b.translate(turnPoint, 0);
        c.translate(thumbRect.width - 1, thumbRect.height / 2);
        d.translate(turnPoint, thumbRect.height - 1);
        e.translate(0, thumbRect.height - 1);

        bright = new Polygon(new int[] { c.x - 1, b.x, a.x, e.x },
                             new int[] { c.y - 1, b.y, a.y, e.y - 1 }, 4);

        dark = new Polygon(new int[] { c.x, d.x, e.x }, new int[] { c.y, d.y,
                                                                   e.y }, 3);

        light = new Polygon(new int[] { c.x - 1, d.x, e.x + 1 },
                            new int[] { c.y, d.y - 1, e.y - 1 }, 3);
        all = new Polygon(new int[] { a.x + 1, b.x, c.x - 2, c.x - 2, d.x,
                                     e.x + 1 }, new int[] { a.y + 1, b.y + 1,
                                                           c.y - 1, c.y,
                                                           d.y - 2, e.y - 2 },
                          6);
      }

    g.setColor(Color.WHITE);
    g.drawPolyline(bright.xpoints, bright.ypoints, bright.npoints);

    g.setColor(Color.BLACK);
    g.drawPolyline(dark.xpoints, dark.ypoints, dark.npoints);

    g.setColor(Color.GRAY);
    g.drawPolyline(light.xpoints, light.ypoints, light.npoints);

    g.setColor(Color.LIGHT_GRAY);
    g.drawPolyline(all.xpoints, all.ypoints, all.npoints);
    g.fillPolygon(all);

    g.setColor(saved_color);
  }

  /**
   * This method sets the position of the thumbRect.
   *
   * @param x The new x position.
   * @param y The new y position.
   */
  public void setThumbLocation(int x, int y)
  {
    Rectangle union = new Rectangle(thumbRect);
    thumbRect.setLocation(x, y);
    SwingUtilities.computeUnion(thumbRect.x, thumbRect.y, thumbRect.width,
                                thumbRect.height, union);
    slider.repaint(union);
  }

  /**
   * Moves the thumb one block in the direction specified (a block is 1/10th
   * of the slider range).   If the slider snaps to ticks, this method is
   * responsible for snapping it to a tick after the thumb has been moved.
   *
   * @param direction  the direction (positive values increment the thumb
   *   position by one block, zero/negative values decrement the thumb position
   *   by one block).
   */
  public void scrollByBlock(int direction)
  {
    int unit = (slider.getMaximum() - slider.getMinimum()) / 10;
    int moveTo = slider.getValue();
    if (direction > 0)
      moveTo += unit;
    else
      moveTo -= unit;

    if (slider.getSnapToTicks())
      moveTo = findClosestTick(moveTo);

    slider.setValue(moveTo);
  }

  /**
   * Moves the thumb one unit in the specified direction. If the slider snaps
   * to ticks, this method is responsible for snapping it to a tick after the
   * thumb has been moved.
   *
   * @param direction  the direction (positive values increment the thumb
   *   position by one, zero/negative values decrement the thumb position by
   *   one).
   */
  public void scrollByUnit(int direction)
  {
    int moveTo = slider.getValue();
    if (direction > 0)
      moveTo++;
    else
      moveTo--;

    if (slider.getSnapToTicks())
      moveTo = findClosestTick(moveTo);

    slider.setValue(moveTo);
  }

  /**
   * This method is called when there has been a click in the track and the
   * thumb needs to be scrolled  on regular intervals. This method is only
   * responsible  for starting the timer and not for stopping it.
   *
   * @param dir The direction to move in.
   */
  protected void scrollDueToClickInTrack(int dir)
  {
    scrollTimer.stop();

    scrollListener.setDirection(dir);
    scrollListener.setScrollByBlock(true);

    scrollTimer.start();
  }

  /**
   * Returns the x-coordinate (relative to the component) for the given slider
   * value.  This method assumes that the <code>trackRect</code> field is
   * set up.
   *
   * @param value  the slider value.
   *
   * @return The x-coordinate.
   */
  protected int xPositionForValue(int value)
  {
    int min = slider.getMinimum();
    int max = slider.getMaximum();
    int len = trackRect.width;
    double range = max - min;
    double pixPerVal = len / range;
    int left = trackRect.x;
    int right = left + trackRect.width - 1;
    int xpos;
    if (! drawInverted())
      xpos = left + (int) Math.round(pixPerVal * ((double) value - min));
    else
      xpos = right - (int) Math.round(pixPerVal * ((double) value - min));
    xpos = Math.max(left, xpos);
    xpos = Math.min(right, xpos);
    return xpos;
  }

  /**
   * Returns the y-coordinate (relative to the component) for the given slider
   * value.  This method assumes that the <code>trackRect</code> field is
   * set up.
   *
   * @param value  the slider value.
   *
   * @return The y-coordinate.
   */
  protected int yPositionForValue(int value)
  {
    int min = slider.getMinimum();
    int max = slider.getMaximum();
    int len = trackRect.height;
    double range = max - min;
    double pixPerVal = len / range;
    int top = trackRect.y;
    int bottom = top + trackRect.height - 1;
    int ypos;
    if (! drawInverted())
      ypos = top + (int) Math.round(pixPerVal * ((double) max - value));
    else
      ypos = top + (int) Math.round(pixPerVal * ((double) value - min));
    ypos = Math.max(top, ypos);
    ypos = Math.min(bottom, ypos);
    return ypos;
  }

  /**
   * This method returns the value in the slider's range given the y
   * coordinate. If the value is out of range, it will  return the closest
   * legal value.
   *
   * @param yPos The y coordinate to calculate a value for.
   *
   * @return The value for the y coordinate.
   */
  public int valueForYPosition(int yPos)
  {
    int min = slider.getMinimum();
    int max = slider.getMaximum();
    int len = trackRect.height;

    int value;

    // If the length is 0, you shouldn't be able to even see where the slider
    // is.  This really shouldn't ever happen, but just in case, we'll return
    // the middle.
    if (len == 0)
      return (max - min) / 2;

    if (! drawInverted())
      value = (len - (yPos - trackRect.y)) * (max - min) / len + min;
    else
      value = (yPos - trackRect.y) * (max - min) / len + min;

    // If this isn't a legal value, then we'll have to move to one now.
    if (value > max)
      value = max;
    else if (value < min)
      value = min;
    return value;
  }

  /**
   * This method returns the value in the slider's range given the x
   * coordinate. If the value is out of range, it will return the closest
   * legal value.
   *
   * @param xPos The x coordinate to calculate a value for.
   *
   * @return The value for the x coordinate.
   */
  public int valueForXPosition(int xPos)
  {
    int min = slider.getMinimum();
    int max = slider.getMaximum();
    int len = trackRect.width;

    int value;

    // If the length is 0, you shouldn't be able to even see where the slider
    // is.  This really shouldn't ever happen, but just in case, we'll return
    // the middle.
    if (len == 0)
      return (max - min) / 2;

    if (! drawInverted())
      value = (xPos - trackRect.x) * (max - min) / len + min;
    else
      value = (len - (xPos - trackRect.x)) * (max - min) / len + min;

    // If this isn't a legal value, then we'll have to move to one now.
    if (value > max)
      value = max;
    else if (value < min)
      value = min;
    return value;
  }

  /**
   * This method finds the closest value that has a tick associated with it.
   * This is package-private to avoid an accessor method.
   *
   * @param value The value to search from.
   *
   * @return The closest value that has a tick associated with it.
   */
  int findClosestTick(int value)
  {
    int min = slider.getMinimum();
    int max = slider.getMaximum();
    int majorSpace = slider.getMajorTickSpacing();
    int minorSpace = slider.getMinorTickSpacing();

    // The default value to return is value + minor or
    // value + major.
    // Initializing at min - value leaves us with a default
    // return value of min, which always has tick marks
    // (if ticks are painted).
    int minor = min - value;
    int major = min - value;

    // If there are no major tick marks or minor tick marks
    // e.g. snap is set to true but no ticks are set, then
    // we can just return the value.
    if (majorSpace <= 0 && minorSpace <= 0)
      return value;

    // First check the major ticks.
    if (majorSpace > 0)
      {
        int lowerBound = (value - min) / majorSpace;
        int majLower = majorSpace * lowerBound + min;
        int majHigher = majorSpace * (lowerBound + 1) + min;

        if (majHigher <= max && majHigher - value <= value - majLower)
          major = majHigher - value;
        else
          major = majLower - value;
      }

    if (minorSpace > 0)
      {
        int lowerBound = value / minorSpace;
        int minLower = minorSpace * lowerBound;
        int minHigher = minorSpace * (lowerBound + 1);

        if (minHigher <= max && minHigher - value <= value - minLower)
          minor = minHigher - value;
        else
          minor = minLower - value;
      }

    // Give preference to minor ticks
    if (Math.abs(minor) > Math.abs(major))
      return value + major;
    else
      return value + minor;
  }

  InputMap getInputMap(int condition)
  {
    if (condition == JComponent.WHEN_FOCUSED)
      return (InputMap) UIManager.get("Slider.focusInputMap");
    return null;
  }

  /**
   * Returns the action map for the {@link JSlider}.  All sliders share
   * a single action map which is created the first time this method is
   * called, then stored in the UIDefaults table for subsequent access.
   *
   * @return The shared action map.
   */
  ActionMap getActionMap()
  {
    ActionMap map = (ActionMap) UIManager.get("Slider.actionMap");

    if (map == null) // first time here
      {
        map = createActionMap();
        if (map != null)
          UIManager.put("Slider.actionMap", map);
      }
    return map;
  }

  /**
   * Creates the action map shared by all {@link JSlider} instances.
   * This method is called once by {@link #getActionMap()} when it
   * finds no action map in the UIDefaults table...after the map is
   * created, it gets added to the defaults table so that subsequent
   * calls to {@link #getActionMap()} will return the same shared
   * instance.
   *
   * @return The action map.
   */
  ActionMap createActionMap()
  {
    ActionMap map = new ActionMapUIResource();
    map.put("positiveUnitIncrement",
            new AbstractAction("positiveUnitIncrement") {
              public void actionPerformed(ActionEvent event)
              {
                JSlider slider = (JSlider) event.getSource();
                BasicSliderUI ui = (BasicSliderUI) slider.getUI();
                if (slider.getInverted())
                  ui.scrollByUnit(BasicSliderUI.NEGATIVE_SCROLL);
                else
                  ui.scrollByUnit(BasicSliderUI.POSITIVE_SCROLL);
              }
            }
    );
    map.put("negativeUnitIncrement",
            new AbstractAction("negativeUnitIncrement") {
              public void actionPerformed(ActionEvent event)
              {
                JSlider slider = (JSlider) event.getSource();
                BasicSliderUI ui = (BasicSliderUI) slider.getUI();
                if (slider.getInverted())
                  ui.scrollByUnit(BasicSliderUI.POSITIVE_SCROLL);
                else
                  ui.scrollByUnit(BasicSliderUI.NEGATIVE_SCROLL);
              }
            }
    );
    map.put("positiveBlockIncrement",
            new AbstractAction("positiveBlockIncrement") {
              public void actionPerformed(ActionEvent event)
              {
                JSlider slider = (JSlider) event.getSource();
                BasicSliderUI ui = (BasicSliderUI) slider.getUI();
                if (slider.getInverted())
                  ui.scrollByBlock(BasicSliderUI.NEGATIVE_SCROLL);
                else
                  ui.scrollByBlock(BasicSliderUI.POSITIVE_SCROLL);
              }
            }
    );
    map.put("negativeBlockIncrement",
            new AbstractAction("negativeBlockIncrement") {
              public void actionPerformed(ActionEvent event)
              {
                JSlider slider = (JSlider) event.getSource();
                BasicSliderUI ui = (BasicSliderUI) slider.getUI();
                if (slider.getInverted())
                  ui.scrollByBlock(BasicSliderUI.POSITIVE_SCROLL);
                else
                  ui.scrollByBlock(BasicSliderUI.NEGATIVE_SCROLL);
              }
            }
    );
    map.put("minScroll",
            new AbstractAction("minScroll") {
              public void actionPerformed(ActionEvent event)
              {
                JSlider slider = (JSlider) event.getSource();
                if (slider.getInverted())
                  slider.setValue(slider.getMaximum());
                else
                  slider.setValue(slider.getMinimum());
              }
            }
    );
    map.put("maxScroll",
            new AbstractAction("maxScroll") {
              public void actionPerformed(ActionEvent event)
              {
                JSlider slider = (JSlider) event.getSource();
                if (slider.getInverted())
                  slider.setValue(slider.getMinimum());
                else
                  slider.setValue(slider.getMaximum());
              }
            }
    );
    return map;
  }

  /**
   * Small utility method to save me from typing the hell out of myself in
   * paint().
   */
  private boolean hitClip(Graphics g, Rectangle r)
  {
    return g.hitClip(r.x, r.y, r.width, r.height);
  }
}