summaryrefslogtreecommitdiff
path: root/libjava/classpath/javax/swing/plaf/basic/BasicTableUI.java
blob: f5a4bcb670d34ee993003b8c33335ca431adb6b0 (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
/* BasicTableUI.java --
   Copyright (C) 2004 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.ComponentOrientation;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.CellRendererPane;
import javax.swing.DefaultCellEditor;
import javax.swing.DefaultListSelectionModel;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.LookAndFeel;
import javax.swing.SwingUtilities;
import javax.swing.TransferHandler;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.event.ChangeEvent;
import javax.swing.event.MouseInputListener;
import javax.swing.plaf.ActionMapUIResource;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.TableUI;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;

public class BasicTableUI extends TableUI
{
  public static ComponentUI createUI(JComponent comp)
  {
    return new BasicTableUI();
  }

  protected FocusListener focusListener;
  protected KeyListener keyListener;
  protected MouseInputListener  mouseInputListener;
  protected CellRendererPane rendererPane;
  protected JTable table;

  /** The normal cell border. */
  Border cellBorder;

  /** The action bound to KeyStrokes. */
  TableAction action;

  /**
   * Listens for changes to the tables properties.
   */
  private PropertyChangeListener propertyChangeListener;

  /**
   * Handles key events for the JTable. Key events should be handled through
   * the InputMap/ActionMap mechanism since JDK1.3. This class is only there
   * for backwards compatibility.
   *
   * @author Roman Kennke (kennke@aicas.com)
   */
  public class KeyHandler implements KeyListener
  {

    /**
     * Receives notification that a key has been pressed and released.
     * Activates the editing session for the focused cell by pressing the
     * character keys.
     *
     * @param event the key event
     */
    public void keyTyped(KeyEvent event)
    {
      // Key events should be handled through the InputMap/ActionMap mechanism
      // since JDK1.3. This class is only there for backwards compatibility.

      // Editor activation is a specific kind of response to ''any''
      // character key. Hence it is handled here.
      if (!table.isEditing() && table.isEnabled())
        {
          int r = table.getSelectedRow();
          int c = table.getSelectedColumn();
          if (table.isCellEditable(r, c))
            table.editCellAt(r, c);
        }
    }

    /**
     * Receives notification that a key has been pressed.
     *
     * @param event the key event
     */
    public void keyPressed(KeyEvent event)
    {
      // Key events should be handled through the InputMap/ActionMap mechanism
      // since JDK1.3. This class is only there for backwards compatibility.
    }

    /**
     * Receives notification that a key has been released.
     *
     * @param event the key event
     */
    public void keyReleased(KeyEvent event)
    {
      // Key events should be handled through the InputMap/ActionMap mechanism
      // since JDK1.3. This class is only there for backwards compatibility.
    }
  }

  public class FocusHandler implements FocusListener
  {
    public void focusGained(FocusEvent e)
    {
      // The only thing that is affected by a focus change seems to be
      // how the lead cell is painted. So we repaint this cell.
      repaintLeadCell();
    }

    public void focusLost(FocusEvent e)
    {
      // The only thing that is affected by a focus change seems to be
      // how the lead cell is painted. So we repaint this cell.
      repaintLeadCell();
    }

    /**
     * Repaints the lead cell in response to a focus change, to refresh
     * the display of the focus indicator.
     */
    private void repaintLeadCell()
    {
      int rowCount = table.getRowCount();
      int columnCount = table.getColumnCount();
      int rowLead = table.getSelectionModel().getLeadSelectionIndex();
      int columnLead = table.getColumnModel().getSelectionModel().
                                                       getLeadSelectionIndex();
      if (rowLead >= 0 && rowLead < rowCount && columnLead >= 0
          && columnLead < columnCount)
        {
          Rectangle dirtyRect = table.getCellRect(rowLead, columnLead, false);
          table.repaint(dirtyRect);
        }
    }
  }

  public class MouseInputHandler implements MouseInputListener
  {
    Point begin, curr;

    private void updateSelection(boolean controlPressed)
    {
      // Update the rows
      int lo_row = table.rowAtPoint(begin);
      int hi_row  = table.rowAtPoint(curr);
      ListSelectionModel rowModel = table.getSelectionModel();
      if (lo_row != -1 && hi_row != -1)
        {
          if (controlPressed && rowModel.getSelectionMode()
              != ListSelectionModel.SINGLE_SELECTION)
            rowModel.addSelectionInterval(lo_row, hi_row);
          else
            rowModel.setSelectionInterval(lo_row, hi_row);
        }

      // Update the columns
      int lo_col = table.columnAtPoint(begin);
      int hi_col = table.columnAtPoint(curr);
      ListSelectionModel colModel = table.getColumnModel().
        getSelectionModel();
      if (lo_col != -1 && hi_col != -1)
        {
          if (controlPressed && colModel.getSelectionMode() !=
              ListSelectionModel.SINGLE_SELECTION)
            colModel.addSelectionInterval(lo_col, hi_col);
          else
            colModel.setSelectionInterval(lo_col, hi_col);
        }
    }

    /**
     * For the double click, start the cell editor.
     */
    public void mouseClicked(MouseEvent e)
    {
      Point p = e.getPoint();
      int row = table.rowAtPoint(p);
      int col = table.columnAtPoint(p);
      if (table.isCellEditable(row, col))
        {
          // If the cell editor is the default editor, we request the
          // number of the required clicks from it. Otherwise,
          // require two clicks (double click).
          TableCellEditor editor = table.getCellEditor(row, col);
          if (editor instanceof DefaultCellEditor)
            {
              DefaultCellEditor ce = (DefaultCellEditor) editor;
              if (e.getClickCount() < ce.getClickCountToStart())
                return;
            }
          table.editCellAt(row, col);
        }
    }

    public void mouseDragged(MouseEvent e)
    {
      if (table.isEnabled())
        {
          curr = new Point(e.getX(), e.getY());
          updateSelection(e.isControlDown());
        }
    }

    public void mouseEntered(MouseEvent e)
    {
      // Nothing to do here.
    }

    public void mouseExited(MouseEvent e)
    {
      // Nothing to do here.
    }

    public void mouseMoved(MouseEvent e)
    {
      // Nothing to do here.
    }

    public void mousePressed(MouseEvent e)
    {
      if (table.isEnabled())
        {
          ListSelectionModel rowModel = table.getSelectionModel();
          ListSelectionModel colModel = table.getColumnModel().getSelectionModel();
          int rowLead = rowModel.getLeadSelectionIndex();
          int colLead = colModel.getLeadSelectionIndex();

          begin = new Point(e.getX(), e.getY());
          curr = new Point(e.getX(), e.getY());
          //if control is pressed and the cell is already selected, deselect it
          if (e.isControlDown() && table.isCellSelected(
              table.rowAtPoint(begin), table.columnAtPoint(begin)))
            {
              table.getSelectionModel().
              removeSelectionInterval(table.rowAtPoint(begin),
                                      table.rowAtPoint(begin));
              table.getColumnModel().getSelectionModel().
              removeSelectionInterval(table.columnAtPoint(begin),
                                      table.columnAtPoint(begin));
            }
          else
            updateSelection(e.isControlDown());

          // If we were editing, but the moved to another cell, stop editing
          if (rowLead != rowModel.getLeadSelectionIndex() ||
              colLead != colModel.getLeadSelectionIndex())
            if (table.isEditing())
              table.editingStopped(new ChangeEvent(e));

          // Must request focus explicitly.
          table.requestFocusInWindow();
        }
    }

    public void mouseReleased(MouseEvent e)
    {
      if (table.isEnabled())
        {
          begin = null;
          curr = null;
        }
    }
  }

  /**
   * Listens for changes to the model property of the JTable and adjusts some
   * settings.
   *
   * @author Roman Kennke (kennke@aicas.com)
   */
  private class PropertyChangeHandler implements PropertyChangeListener
  {
    /**
     * Receives notification if one of the JTable's properties changes.
     *
     * @param ev the property change event
     */
    public void propertyChange(PropertyChangeEvent ev)
    {
      String propName = ev.getPropertyName();
      if (propName.equals("model"))
        {
          ListSelectionModel rowSel = table.getSelectionModel();
          rowSel.clearSelection();
          ListSelectionModel colSel = table.getColumnModel().getSelectionModel();
          colSel.clearSelection();
          TableModel model = table.getModel();

          // Adjust lead and anchor selection indices of the row and column
          // selection models.
          if (model.getRowCount() > 0)
            {
              rowSel.setAnchorSelectionIndex(0);
              rowSel.setLeadSelectionIndex(0);
            }
          else
            {
              rowSel.setAnchorSelectionIndex(-1);
              rowSel.setLeadSelectionIndex(-1);
            }
          if (model.getColumnCount() > 0)
            {
              colSel.setAnchorSelectionIndex(0);
              colSel.setLeadSelectionIndex(0);
            }
          else
            {
              colSel.setAnchorSelectionIndex(-1);
              colSel.setLeadSelectionIndex(-1);
            }
        }
    }
  }

  protected FocusListener createFocusListener()
  {
    return new FocusHandler();
  }

  protected MouseInputListener createMouseInputListener()
  {
    return new MouseInputHandler();
  }


  /**
   * Creates and returns a key listener for the JTable.
   *
   * @return a key listener for the JTable
   */
  protected KeyListener createKeyListener()
  {
    return new KeyHandler();
  }

  /**
   * Return the maximum size of the table. The maximum height is the row
    * height times the number of rows. The maximum width is the sum of
    * the maximum widths of each column.
    *
    *  @param comp the component whose maximum size is being queried,
    *  this is ignored.
    *  @return a Dimension object representing the maximum size of the table,
    *  or null if the table has no elements.
   */
  public Dimension getMaximumSize(JComponent comp)
  {
    int maxTotalColumnWidth = 0;
    for (int i = 0; i < table.getColumnCount(); i++)
      maxTotalColumnWidth += table.getColumnModel().getColumn(i).getMaxWidth();

    return new Dimension(maxTotalColumnWidth, getHeight());
  }

  /**
   * Return the minimum size of the table. The minimum height is the row
    * height times the number of rows. The minimum width is the sum of
    * the minimum widths of each column.
    *
    *  @param comp the component whose minimum size is being queried,
    *  this is ignored.
    *  @return a Dimension object representing the minimum size of the table,
    *  or null if the table has no elements.
   */
  public Dimension getMinimumSize(JComponent comp)
  {
    int minTotalColumnWidth = 0;
    for (int i = 0; i < table.getColumnCount(); i++)
      minTotalColumnWidth += table.getColumnModel().getColumn(i).getMinWidth();

    return new Dimension(minTotalColumnWidth, getHeight());
  }

  /**
   * Returns the preferred size for the table of that UI.
   *
   * @param comp ignored, the <code>table</code> field is used instead
   *
   * @return the preferred size for the table of that UI
   */
  public Dimension getPreferredSize(JComponent comp)
  {
    int prefTotalColumnWidth = 0;
    TableColumnModel tcm = table.getColumnModel();

    for (int i = 0; i < tcm.getColumnCount(); i++)
      {
        TableColumn col = tcm.getColumn(i);
        prefTotalColumnWidth += col.getPreferredWidth();
      }

    return new Dimension(prefTotalColumnWidth, getHeight());
  }

  /**
   * Returns the table height. This helper method is used by
   * {@link #getMinimumSize(JComponent)}, {@link #getPreferredSize(JComponent)}
   * and {@link #getMaximumSize(JComponent)} to determine the table height.
   *
   * @return the table height
   */
  private int getHeight()
  {
    int height = 0;
    int rowCount = table.getRowCount();
    if (rowCount > 0 && table.getColumnCount() > 0)
      {
        Rectangle r = table.getCellRect(rowCount - 1, 0, true);
        height = r.y + r.height;
      }
    return height;
  }

  protected void installDefaults()
  {
    LookAndFeel.installColorsAndFont(table, "Table.background",
                                     "Table.foreground", "Table.font");
    table.setGridColor(UIManager.getColor("Table.gridColor"));
    table.setSelectionForeground(UIManager.getColor("Table.selectionForeground"));
    table.setSelectionBackground(UIManager.getColor("Table.selectionBackground"));
    table.setOpaque(true);
  }

  /**
   * Installs keyboard actions on the table.
   */
  protected void installKeyboardActions()
  {
    // Install the input map.
    InputMap inputMap =
      (InputMap) SharedUIDefaults.get("Table.ancestorInputMap");
    SwingUtilities.replaceUIInputMap(table,
                                 JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT,
                                 inputMap);

    // FIXME: The JDK uses a LazyActionMap for parentActionMap
    SwingUtilities.replaceUIActionMap(table, getActionMap());

  }

  /**
   * Fetches the action map from  the UI defaults, or create a new one
   * if the action map hasn't been initialized.
   *
   * @return the action map
   */
  private ActionMap getActionMap()
  {
    ActionMap am = (ActionMap) UIManager.get("Table.actionMap");
    if (am == null)
      {
        am = createDefaultActions();
        UIManager.getLookAndFeelDefaults().put("Table.actionMap", am);
      }
    return am;
  }

  private ActionMap createDefaultActions()
  {
    ActionMapUIResource am = new ActionMapUIResource();
    Action action = new TableAction();

    am.put("cut", TransferHandler.getCutAction());
    am.put("copy", TransferHandler.getCopyAction());
    am.put("paste", TransferHandler.getPasteAction());

    am.put("cancel", action);
    am.put("selectAll", action);
    am.put("clearSelection", action);
    am.put("startEditing", action);

    am.put("selectNextRow", action);
    am.put("selectNextRowCell", action);
    am.put("selectNextRowExtendSelection", action);
    am.put("selectNextRowChangeLead", action);

    am.put("selectPreviousRow", action);
    am.put("selectPreviousRowCell", action);
    am.put("selectPreviousRowExtendSelection", action);
    am.put("selectPreviousRowChangeLead", action);

    am.put("selectNextColumn", action);
    am.put("selectNextColumnCell", action);
    am.put("selectNextColumnExtendSelection", action);
    am.put("selectNextColumnChangeLead", action);

    am.put("selectPreviousColumn", action);
    am.put("selectPreviousColumnCell", action);
    am.put("selectPreviousColumnExtendSelection", action);
    am.put("selectPreviousColumnChangeLead", action);

    am.put("scrollLeftChangeSelection", action);
    am.put("scrollLeftExtendSelection", action);
    am.put("scrollRightChangeSelection", action);
    am.put("scrollRightExtendSelection", action);

    am.put("scrollUpChangeSelection", action);
    am.put("scrollUpExtendSelection", action);
    am.put("scrollDownChangeSelection", action);
    am.put("scrolldownExtendSelection", action);

    am.put("selectFirstColumn", action);
    am.put("selectFirstColumnExtendSelection", action);
    am.put("selectLastColumn", action);
    am.put("selectLastColumnExtendSelection", action);

    am.put("selectFirstRow", action);
    am.put("selectFirstRowExtendSelection", action);
    am.put("selectLastRow", action);
    am.put("selectLastRowExtendSelection", action);

    am.put("addToSelection", action);
    am.put("toggleAndAnchor", action);
    am.put("extendTo", action);
    am.put("moveSelectionTo", action);

    return am;
  }

  /**
   * This class implements the actions that we want to happen
   * when specific keys are pressed for the JTable.  The actionPerformed
   * method is called when a key that has been registered for the JTable
   * is received.
   */
  private static class TableAction
    extends AbstractAction
  {
    /**
     * What to do when this action is called.
     *
     * @param e the ActionEvent that caused this action.
     */
    public void actionPerformed(ActionEvent e)
    {
      JTable table = (JTable) e.getSource();

      DefaultListSelectionModel rowModel
          = (DefaultListSelectionModel) table.getSelectionModel();
      DefaultListSelectionModel colModel
          = (DefaultListSelectionModel) table.getColumnModel().getSelectionModel();

      int rowLead = rowModel.getLeadSelectionIndex();
      int rowMax = table.getModel().getRowCount() - 1;

      int colLead = colModel.getLeadSelectionIndex();
      int colMax = table.getModel().getColumnCount() - 1;

      // The command with which the action has been called is stored
      // in this undocumented action value. This allows us to have only
      // one Action instance to serve all keyboard input for JTable.
      String command = (String) getValue("__command__");
      if (command.equals("selectPreviousRowExtendSelection"))
        {
          rowModel.setLeadSelectionIndex(Math.max(rowLead - 1, 0));
        }
      else if (command.equals("selectLastColumn"))
        {
          colModel.setSelectionInterval(colMax, colMax);
        }
      else if (command.equals("startEditing"))
        {
          if (table.isCellEditable(rowLead, colLead))
            table.editCellAt(rowLead, colLead);
        }
      else if (command.equals("selectFirstRowExtendSelection"))
        {
          rowModel.setLeadSelectionIndex(0);
        }
      else if (command.equals("selectFirstColumn"))
        {
          colModel.setSelectionInterval(0, 0);
        }
      else if (command.equals("selectFirstColumnExtendSelection"))
        {
          colModel.setLeadSelectionIndex(0);
        }
      else if (command.equals("selectLastRow"))
        {
          rowModel.setSelectionInterval(rowMax, rowMax);
        }
      else if (command.equals("selectNextRowExtendSelection"))
        {
          rowModel.setLeadSelectionIndex(Math.min(rowLead + 1, rowMax));
        }
      else if (command.equals("selectFirstRow"))
        {
          rowModel.setSelectionInterval(0, 0);
        }
      else if (command.equals("selectNextColumnExtendSelection"))
        {
          colModel.setLeadSelectionIndex(Math.min(colLead + 1, colMax));
        }
      else if (command.equals("selectLastColumnExtendSelection"))
        {
          colModel.setLeadSelectionIndex(colMax);
        }
      else if (command.equals("selectPreviousColumnExtendSelection"))
        {
          colModel.setLeadSelectionIndex(Math.max(colLead - 1, 0));
        }
      else if (command.equals("selectNextRow"))
        {
          rowModel.setSelectionInterval(Math.min(rowLead + 1, rowMax),
                                        Math.min(rowLead + 1, rowMax));
        }
      else if (command.equals("scrollUpExtendSelection"))
        {
          int target;
          if (rowLead == getFirstVisibleRowIndex(table))
            target = Math.max(0, rowLead - (getLastVisibleRowIndex(table)
                - getFirstVisibleRowIndex(table) + 1));
          else
            target = getFirstVisibleRowIndex(table);

          rowModel.setLeadSelectionIndex(target);
          colModel.setLeadSelectionIndex(colLead);
        }
      else if (command.equals("selectPreviousRow"))
        {
          rowModel.setSelectionInterval(Math.max(rowLead - 1, 0),
                                        Math.max(rowLead - 1, 0));
        }
      else if (command.equals("scrollRightChangeSelection"))
        {
          int target;
          if (colLead == getLastVisibleColumnIndex(table))
            target = Math.min(colMax, colLead
                              + (getLastVisibleColumnIndex(table)
                              - getFirstVisibleColumnIndex(table) + 1));
          else
            target = getLastVisibleColumnIndex(table);

          colModel.setSelectionInterval(target, target);
          rowModel.setSelectionInterval(rowLead, rowLead);
        }
      else if (command.equals("selectPreviousColumn"))
        {
          colModel.setSelectionInterval(Math.max(colLead - 1, 0),
                                        Math.max(colLead - 1, 0));
        }
      else if (command.equals("scrollLeftChangeSelection"))
        {
          int target;
          if (colLead == getFirstVisibleColumnIndex(table))
            target = Math.max(0, colLead - (getLastVisibleColumnIndex(table)
                                 - getFirstVisibleColumnIndex(table) + 1));
          else
            target = getFirstVisibleColumnIndex(table);

          colModel.setSelectionInterval(target, target);
          rowModel.setSelectionInterval(rowLead, rowLead);
        }
      else if (command.equals("clearSelection"))
        {
          table.clearSelection();
        }
      else if (command.equals("cancel"))
        {
          // FIXME: implement other parts of "cancel" like undo-ing last
          // selection.  Right now it just calls editingCancelled if
          // we're currently editing.
          if (table.isEditing())
            table.editingCanceled(new ChangeEvent("cancel"));
        }
      else if (command.equals("selectNextRowCell")
               || command.equals("selectPreviousRowCell")
               || command.equals("selectNextColumnCell")
               || command.equals("selectPreviousColumnCell"))
        {
          // If nothing is selected, select the first cell in the table
          if (table.getSelectedRowCount() == 0 &&
              table.getSelectedColumnCount() == 0)
            {
              rowModel.setSelectionInterval(0, 0);
              colModel.setSelectionInterval(0, 0);
              return;
            }

          // If the lead selection index isn't selected (ie a remove operation
          // happened, then set the lead to the first selected cell in the
          // table
          if (!table.isCellSelected(rowLead, colLead))
            {
              rowModel.addSelectionInterval(rowModel.getMinSelectionIndex(),
                                            rowModel.getMinSelectionIndex());
              colModel.addSelectionInterval(colModel.getMinSelectionIndex(),
                                            colModel.getMinSelectionIndex());
              return;
            }

          // multRowsSelected and multColsSelected tell us if multiple rows or
          // columns are selected, respectively
          boolean multRowsSelected, multColsSelected;
          multRowsSelected = table.getSelectedRowCount() > 1 &&
            table.getRowSelectionAllowed();

          multColsSelected = table.getSelectedColumnCount() > 1 &&
            table.getColumnSelectionAllowed();

          // If there is just one selection, select the next cell, and wrap
          // when you get to the edges of the table.
          if (!multColsSelected && !multRowsSelected)
            {
              if (command.indexOf("Column") != -1)
                advanceSingleSelection(colModel, colMax, rowModel, rowMax,
                    command.equals("selectPreviousColumnCell"));
              else
                advanceSingleSelection(rowModel, rowMax, colModel, colMax,
                    command.equals("selectPreviousRowCell"));
              return;
            }


          // rowMinSelected and rowMaxSelected are the minimum and maximum
          // values respectively of selected cells in the row selection model
          // Similarly for colMinSelected and colMaxSelected.
          int rowMaxSelected = table.getRowSelectionAllowed() ?
            rowModel.getMaxSelectionIndex() : table.getModel().getRowCount() - 1;
          int rowMinSelected = table.getRowSelectionAllowed() ?
            rowModel.getMinSelectionIndex() : 0;
          int colMaxSelected = table.getColumnSelectionAllowed() ?
            colModel.getMaxSelectionIndex() :
            table.getModel().getColumnCount() - 1;
          int colMinSelected = table.getColumnSelectionAllowed() ?
            colModel.getMinSelectionIndex() : 0;

          // If there are multiple rows and columns selected, select the next
          // cell and wrap at the edges of the selection.
          if (command.indexOf("Column") != -1)
            advanceMultipleSelection(table, colModel, colMinSelected,
                                     colMaxSelected, rowModel, rowMinSelected,
                                     rowMaxSelected,
                                    command.equals("selectPreviousColumnCell"),
                                    true);

          else
            advanceMultipleSelection(table, rowModel, rowMinSelected,
                                     rowMaxSelected, colModel, colMinSelected,
                                     colMaxSelected,
                                     command.equals("selectPreviousRowCell"),
                                     false);
        }
      else if (command.equals("selectNextColumn"))
        {
          colModel.setSelectionInterval(Math.min(colLead + 1, colMax),
                                        Math.min(colLead + 1, colMax));
        }
      else if (command.equals("scrollLeftExtendSelection"))
        {
          int target;
          if (colLead == getFirstVisibleColumnIndex(table))
            target = Math.max(0, colLead - (getLastVisibleColumnIndex(table)
                                 - getFirstVisibleColumnIndex(table) + 1));
          else
            target = getFirstVisibleColumnIndex(table);

          colModel.setLeadSelectionIndex(target);
          rowModel.setLeadSelectionIndex(rowLead);
        }
      else if (command.equals("scrollDownChangeSelection"))
        {
          int target;
          if (rowLead == getLastVisibleRowIndex(table))
            target = Math.min(rowMax, rowLead + (getLastVisibleRowIndex(table)
                                      - getFirstVisibleRowIndex(table) + 1));
          else
            target = getLastVisibleRowIndex(table);

          rowModel.setSelectionInterval(target, target);
          colModel.setSelectionInterval(colLead, colLead);
        }
      else if (command.equals("scrollRightExtendSelection"))
        {
          int target;
          if (colLead == getLastVisibleColumnIndex(table))
            target = Math.min(colMax, colLead + (getLastVisibleColumnIndex(table)
                - getFirstVisibleColumnIndex(table) + 1));
          else
            target = getLastVisibleColumnIndex(table);

          colModel.setLeadSelectionIndex(target);
          rowModel.setLeadSelectionIndex(rowLead);
        }
      else if (command.equals("selectAll"))
        {
          table.selectAll();
        }
      else if (command.equals("selectLastRowExtendSelection"))
        {
          rowModel.setLeadSelectionIndex(rowMax);
          colModel.setLeadSelectionIndex(colLead);
        }
      else if (command.equals("scrollDownExtendSelection"))
        {
          int target;
          if (rowLead == getLastVisibleRowIndex(table))
            target = Math.min(rowMax, rowLead + (getLastVisibleRowIndex(table)
                - getFirstVisibleRowIndex(table) + 1));
          else
            target = getLastVisibleRowIndex(table);

          rowModel.setLeadSelectionIndex(target);
          colModel.setLeadSelectionIndex(colLead);
        }
      else if (command.equals("scrollUpChangeSelection"))
        {
          int target;
          if (rowLead == getFirstVisibleRowIndex(table))
            target = Math.max(0, rowLead - (getLastVisibleRowIndex(table)
                - getFirstVisibleRowIndex(table) + 1));
          else
            target = getFirstVisibleRowIndex(table);

          rowModel.setSelectionInterval(target, target);
          colModel.setSelectionInterval(colLead, colLead);
        }
      else if (command.equals("selectNextRowChangeLead"))
          {
            if (rowModel.getSelectionMode()
                != ListSelectionModel.MULTIPLE_INTERVAL_SELECTION)
              {
                // just "selectNextRow"
                rowModel.setSelectionInterval(Math.min(rowLead + 1, rowMax),
                                              Math.min(rowLead + 1, rowMax));
                colModel.setSelectionInterval(colLead, colLead);
              }
            else
              rowModel.moveLeadSelectionIndex(Math.min(rowLead + 1, rowMax));
          }
      else if (command.equals("selectPreviousRowChangeLead"))
        {
          if (rowModel.getSelectionMode()
              != ListSelectionModel.MULTIPLE_INTERVAL_SELECTION)
            {
              // just selectPreviousRow
              rowModel.setSelectionInterval(Math.max(rowLead - 1, 0),
                                            Math.min(rowLead - 1, 0));
              colModel.setSelectionInterval(colLead, colLead);
            }
          else
            rowModel.moveLeadSelectionIndex(Math.max(rowLead - 1, 0));
        }
      else if (command.equals("selectNextColumnChangeLead"))
        {
          if (colModel.getSelectionMode()
              != ListSelectionModel.MULTIPLE_INTERVAL_SELECTION)
            {
              // just selectNextColumn
              rowModel.setSelectionInterval(rowLead, rowLead);
              colModel.setSelectionInterval(Math.min(colLead + 1, colMax),
                                            Math.min(colLead + 1, colMax));
            }
          else
            colModel.moveLeadSelectionIndex(Math.min(colLead + 1, colMax));
        }
      else if (command.equals("selectPreviousColumnChangeLead"))
        {
          if (colModel.getSelectionMode()
              != ListSelectionModel.MULTIPLE_INTERVAL_SELECTION)
            {
              // just selectPreviousColumn
              rowModel.setSelectionInterval(rowLead, rowLead);
              colModel.setSelectionInterval(Math.max(colLead - 1, 0),
                                            Math.max(colLead - 1, 0));

            }
          else
            colModel.moveLeadSelectionIndex(Math.max(colLead - 1, 0));
        }
      else if (command.equals("addToSelection"))
          {
            if (!table.isEditing())
              {
                int oldRowAnchor = rowModel.getAnchorSelectionIndex();
                int oldColAnchor = colModel.getAnchorSelectionIndex();
                rowModel.addSelectionInterval(rowLead, rowLead);
                colModel.addSelectionInterval(colLead, colLead);
                rowModel.setAnchorSelectionIndex(oldRowAnchor);
                colModel.setAnchorSelectionIndex(oldColAnchor);
              }
          }
      else if (command.equals("extendTo"))
        {
          rowModel.setSelectionInterval(rowModel.getAnchorSelectionIndex(),
                                        rowLead);
          colModel.setSelectionInterval(colModel.getAnchorSelectionIndex(),
                                        colLead);
        }
      else if (command.equals("toggleAndAnchor"))
        {
          if (rowModel.isSelectedIndex(rowLead))
            rowModel.removeSelectionInterval(rowLead, rowLead);
          else
            rowModel.addSelectionInterval(rowLead, rowLead);

          if (colModel.isSelectedIndex(colLead))
            colModel.removeSelectionInterval(colLead, colLead);
          else
            colModel.addSelectionInterval(colLead, colLead);

          rowModel.setAnchorSelectionIndex(rowLead);
          colModel.setAnchorSelectionIndex(colLead);
        }
      else if (command.equals("stopEditing"))
        {
          table.editingStopped(new ChangeEvent(command));
        }
      else
        {
          // If we're here that means we bound this TableAction class
          // to a keyboard input but we either want to ignore that input
          // or we just haven't implemented its action yet.

          // Uncomment the following line to print the names of unused bindings
          // when their keys are pressed

          // System.out.println ("not implemented: "+e.getActionCommand());
        }

      // Any commands whose keyStrokes should be used by the Editor should not
      // cause editing to be stopped: ie, the SPACE sends "addToSelection" but
      // if the table is in editing mode, the space should not cause us to stop
      // editing because it should be used by the Editor.
      if (table.isEditing() && command != "startEditing"
          && command != "addToSelection")
        table.editingStopped(new ChangeEvent("update"));

      table.scrollRectToVisible(table.getCellRect(
          rowModel.getLeadSelectionIndex(), colModel.getLeadSelectionIndex(),
          false));
    }

    /**
     * Returns the column index of the first visible column.
     * @return the column index of the first visible column.
     */
    int getFirstVisibleColumnIndex(JTable table)
    {
      ComponentOrientation or = table.getComponentOrientation();
      Rectangle r = table.getVisibleRect();
      if (!or.isLeftToRight())
        r.translate((int) r.getWidth() - 1, 0);
      return table.columnAtPoint(r.getLocation());
    }

    /**
     * Returns the column index of the last visible column.
     *
     */
    int getLastVisibleColumnIndex(JTable table)
    {
      ComponentOrientation or = table.getComponentOrientation();
      Rectangle r = table.getVisibleRect();
      if (or.isLeftToRight())
        r.translate((int) r.getWidth() - 1, 0);
      return table.columnAtPoint(r.getLocation());
    }

    /**
     * Returns the row index of the first visible row.
     *
     */
    int getFirstVisibleRowIndex(JTable table)
    {
      ComponentOrientation or = table.getComponentOrientation();
      Rectangle r = table.getVisibleRect();
      if (!or.isLeftToRight())
        r.translate((int) r.getWidth() - 1, 0);
      return table.rowAtPoint(r.getLocation());
    }

    /**
     * Returns the row index of the last visible row.
     *
     */
    int getLastVisibleRowIndex(JTable table)
    {
      ComponentOrientation or = table.getComponentOrientation();
      Rectangle r = table.getVisibleRect();
      r.translate(0, (int) r.getHeight() - 1);
      if (or.isLeftToRight())
        r.translate((int) r.getWidth() - 1, 0);
      // The next if makes sure that we don't return -1 simply because
      // there is white space at the bottom of the table (ie, the display
      // area is larger than the table)
      if (table.rowAtPoint(r.getLocation()) == -1)
        {
          if (getFirstVisibleRowIndex(table) == -1)
            return -1;
          else
            return table.getModel().getRowCount() - 1;
        }
      return table.rowAtPoint(r.getLocation());
    }

    /**
     * A helper method for the key bindings.  Used because the actions
     * for TAB, SHIFT-TAB, ENTER, and SHIFT-ENTER are very similar.
     *
     * Selects the next (previous if SHIFT pressed) column for TAB, or row for
     * ENTER from within the currently selected cells.
     *
     * @param firstModel the ListSelectionModel for columns (TAB) or
     * rows (ENTER)
     * @param firstMin the first selected index in firstModel
     * @param firstMax the last selected index in firstModel
     * @param secondModel the ListSelectionModel for rows (TAB) or
     * columns (ENTER)
     * @param secondMin the first selected index in secondModel
     * @param secondMax the last selected index in secondModel
     * @param reverse true if shift was held for the event
     * @param eventIsTab true if TAB was pressed, false if ENTER pressed
     */
    void advanceMultipleSelection(JTable table, ListSelectionModel firstModel,
                                  int firstMin,
                                  int firstMax, ListSelectionModel secondModel,
                                  int secondMin, int secondMax, boolean reverse,
                                  boolean eventIsTab)
    {
      // If eventIsTab, all the "firsts" correspond to columns, otherwise, to
      // rows "seconds" correspond to the opposite
      int firstLead = firstModel.getLeadSelectionIndex();
      int secondLead = secondModel.getLeadSelectionIndex();
      int numFirsts = eventIsTab ?
        table.getModel().getColumnCount() : table.getModel().getRowCount();
      int numSeconds = eventIsTab ?
        table.getModel().getRowCount() : table.getModel().getColumnCount();

      // check if we have to wrap the "firsts" around, going to the other side
      if ((firstLead == firstMax && !reverse) ||
          (reverse && firstLead == firstMin))
        {
          firstModel.addSelectionInterval(reverse ? firstMax : firstMin,
                                          reverse ? firstMax : firstMin);

          // check if we have to wrap the "seconds"
          if ((secondLead == secondMax && !reverse) ||
              (reverse && secondLead == secondMin))
            secondModel.addSelectionInterval(reverse ? secondMax : secondMin,
                                             reverse ? secondMax : secondMin);

          // if we're not wrapping the seconds, we have to find out where we
          // are within the secondModel and advance to the next cell (or
          // go back to the previous cell if reverse == true)
          else
            {
              int[] secondsSelected;
              if (eventIsTab && table.getRowSelectionAllowed() ||
                  !eventIsTab && table.getColumnSelectionAllowed())
                secondsSelected = eventIsTab ?
                  table.getSelectedRows() : table.getSelectedColumns();
              else
                {
                  // if row selection is not allowed, then the entire column gets
                  // selected when you click on it, so consider ALL rows selected
                  secondsSelected = new int[numSeconds];
                  for (int i = 0; i < numSeconds; i++)
                  secondsSelected[i] = i;
                }

              // and now find the "next" index within the model
              int secondIndex = reverse ? secondsSelected.length - 1 : 0;
              if (!reverse)
                while (secondsSelected[secondIndex] <= secondLead)
                  secondIndex++;
              else
                while (secondsSelected[secondIndex] >= secondLead)
                  secondIndex--;

              // and select it - updating the lead selection index
              secondModel.addSelectionInterval(secondsSelected[secondIndex],
                                               secondsSelected[secondIndex]);
            }
        }
      // We didn't have to wrap the firsts, so just find the "next" first
      // and select it, we don't have to change "seconds"
      else
        {
          int[] firstsSelected;
          if (eventIsTab && table.getColumnSelectionAllowed() ||
              !eventIsTab && table.getRowSelectionAllowed())
            firstsSelected = eventIsTab ?
              table.getSelectedColumns() : table.getSelectedRows();
          else
            {
              // if selection not allowed, consider ALL firsts to be selected
              firstsSelected = new int[numFirsts];
              for (int i = 0; i < numFirsts; i++)
                firstsSelected[i] = i;
            }
          int firstIndex = reverse ? firstsSelected.length - 1 : 0;
          if (!reverse)
            while (firstsSelected[firstIndex] <= firstLead)
              firstIndex++;
          else
            while (firstsSelected[firstIndex] >= firstLead)
              firstIndex--;
          firstModel.addSelectionInterval(firstsSelected[firstIndex],
                                          firstsSelected[firstIndex]);
          secondModel.addSelectionInterval(secondLead, secondLead);
        }
    }

    /**
     * A helper method for the key  bindings. Used because the actions
     * for TAB, SHIFT-TAB, ENTER, and SHIFT-ENTER are very similar.
     *
     * Selects the next (previous if SHIFT pressed) column (TAB) or row (ENTER)
     * in the table, changing the current selection.  All cells in the table
     * are eligible, not just the ones that are currently selected.
     * @param firstModel the ListSelectionModel for columns (TAB) or rows
     * (ENTER)
     * @param firstMax the last index in firstModel
     * @param secondModel the ListSelectionModel for rows (TAB) or columns
     * (ENTER)
     * @param secondMax the last index in secondModel
     * @param reverse true if SHIFT was pressed for the event
     */

    void advanceSingleSelection(ListSelectionModel firstModel, int firstMax,
                                ListSelectionModel secondModel, int secondMax,
                                boolean reverse)
    {
      // for TABs, "first" corresponds to columns and "seconds" to rows.
      // the opposite is true for ENTERs
      int firstLead = firstModel.getLeadSelectionIndex();
      int secondLead = secondModel.getLeadSelectionIndex();

      // if we are going backwards subtract 2 because we later add 1
      // for a net change of -1
      if (reverse && (firstLead == 0))
        {
          // check if we have to wrap around
          if (secondLead == 0)
            secondLead += secondMax + 1;
          secondLead -= 2;
        }

      // do we have to wrap the "seconds"?
      if (reverse && (firstLead == 0) || !reverse && (firstLead == firstMax))
        secondModel.setSelectionInterval((secondLead + 1) % (secondMax + 1),
                                         (secondLead + 1) % (secondMax + 1));
      // if not, just reselect the current lead
      else
        secondModel.setSelectionInterval(secondLead, secondLead);

      // if we are going backwards, subtract 2  because we add 1 later
      // for net change of -1
      if (reverse)
        {
          // check for wraparound
          if (firstLead == 0)
            firstLead += firstMax + 1;
          firstLead -= 2;
        }
      // select the next "first"
      firstModel.setSelectionInterval((firstLead + 1) % (firstMax + 1),
                                      (firstLead + 1) % (firstMax + 1));
    }
  }

  protected void installListeners()
  {
    if (focusListener == null)
      focusListener = createFocusListener();
    table.addFocusListener(focusListener);
    if (keyListener == null)
      keyListener = createKeyListener();
    table.addKeyListener(keyListener);
    if (mouseInputListener == null)
      mouseInputListener = createMouseInputListener();
    table.addMouseListener(mouseInputListener);
    table.addMouseMotionListener(mouseInputListener);
    if (propertyChangeListener == null)
      propertyChangeListener = new PropertyChangeHandler();
    table.addPropertyChangeListener(propertyChangeListener);
  }

  /**
   * Uninstalls UI defaults that have been installed by
   * {@link #installDefaults()}.
   */
  protected void uninstallDefaults()
  {
    // Nothing to do here for now.
  }

  /**
   * Uninstalls the keyboard actions that have been installed by
   * {@link #installKeyboardActions()}.
   */
  protected void uninstallKeyboardActions()
  {
    SwingUtilities.replaceUIInputMap(table, JComponent.
                                     WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, null);
    SwingUtilities.replaceUIActionMap(table, null);
  }

  protected void uninstallListeners()
  {
    table.removeFocusListener(focusListener);
    table.removeKeyListener(keyListener);
    table.removeMouseListener(mouseInputListener);
    table.removeMouseMotionListener(mouseInputListener);
    table.removePropertyChangeListener(propertyChangeListener);
    propertyChangeListener = null;
  }

  public void installUI(JComponent comp)
  {
    table = (JTable) comp;
    rendererPane = new CellRendererPane();
    table.add(rendererPane);

    installDefaults();
    installKeyboardActions();
    installListeners();
  }

  public void uninstallUI(JComponent c)
  {
    uninstallListeners();
    uninstallKeyboardActions();
    uninstallDefaults();

    table.remove(rendererPane);
    rendererPane = null;
    table = null;
  }

  /**
   * Paints a single cell in the table.
   *
   * @param g The graphics context to paint in
   * @param row The row number to paint
   * @param col The column number to paint
   * @param bounds The bounds of the cell to paint, assuming a coordinate
   * system beginning at <code>(0,0)</code> in the upper left corner of the
   * table
   * @param rend A cell renderer to paint with
   */
  void paintCell(Graphics g, int row, int col, Rectangle bounds,
                 TableCellRenderer rend)
  {
    Component comp = table.prepareRenderer(rend, row, col);
    rendererPane.paintComponent(g, comp, table, bounds);
  }

  /**
   * Paint the associated table.
   */
  public void paint(Graphics gfx, JComponent ignored)
  {
    int ncols = table.getColumnCount();
    int nrows = table.getRowCount();
    if (nrows == 0 || ncols == 0)
      return;

    Rectangle clip = gfx.getClipBounds();

    // Determine the range of cells that are within the clip bounds.
    Point p1 = new Point(clip.x, clip.y);
    int c0 = table.columnAtPoint(p1);
    if (c0 == -1)
      c0 = 0;
    int r0 = table.rowAtPoint(p1);
    if (r0 == -1)
      r0 = 0;
    Point p2 = new Point(clip.x + clip.width, clip.y + clip.height);
    int cn = table.columnAtPoint(p2);
    if (cn == -1)
      cn = table.getColumnCount() - 1;
    int rn = table.rowAtPoint(p2);
    if (rn == -1)
      rn = table.getRowCount() - 1;

    int columnMargin = table.getColumnModel().getColumnMargin();
    int rowMargin = table.getRowMargin();

    TableColumnModel cmodel = table.getColumnModel();
    int[] widths = new int[cn + 1];
    for (int i = c0; i <= cn; i++)
      {
        widths[i] = cmodel.getColumn(i).getWidth() - columnMargin;
      }

    Rectangle bounds = table.getCellRect(r0, c0, false);
    // The left boundary of the area being repainted.
    int left = bounds.x;

    // The top boundary of the area being repainted.
    int top = bounds.y;

    // The bottom boundary of the area being repainted.
    int bottom;

    // paint the cell contents
    Color grid = table.getGridColor();
    for (int r = r0; r <= rn; ++r)
      {
        for (int c = c0; c <= cn; ++c)
          {
            bounds.width = widths[c];
            paintCell(gfx, r, c, bounds, table.getCellRenderer(r, c));
            bounds.x += widths[c] + columnMargin;
          }
        bounds.x = left;
        bounds.y += table.getRowHeight(r);
        // Update row height for tables with custom heights.
        bounds.height = table.getRowHeight(r + 1) - rowMargin;
      }

    bottom = bounds.y - rowMargin;

    // paint vertical grid lines
    if (grid != null && table.getShowVerticalLines())
      {
        Color save = gfx.getColor();
        gfx.setColor(grid);
        int x = left - columnMargin;
        for (int c = c0; c <= cn; ++c)
          {
            // The vertical grid is draw right from the cells, so we
            // add before drawing.
            x += widths[c] + columnMargin;
            gfx.drawLine(x, top, x, bottom);
          }
        gfx.setColor(save);
      }

    // paint horizontal grid lines
    if (grid != null && table.getShowHorizontalLines())
      {
        Color save = gfx.getColor();
        gfx.setColor(grid);
        int y = top - rowMargin;
        for (int r = r0; r <= rn; ++r)
          {
            // The horizontal grid is draw below the cells, so we
            // add before drawing.
            y += table.getRowHeight(r);
            gfx.drawLine(left, y, p2.x, y);
          }
        gfx.setColor(save);
      }
  }
}