1 /*
   2  * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package javax.swing;
  27 
  28 import java.util.*;
  29 
  30 import java.applet.Applet;
  31 import java.awt.*;
  32 import java.awt.event.*;
  33 import java.awt.print.*;
  34 
  35 import java.beans.*;
  36 
  37 import java.io.ObjectOutputStream;
  38 import java.io.ObjectInputStream;
  39 import java.io.IOException;
  40 
  41 import javax.accessibility.*;
  42 
  43 import javax.swing.event.*;
  44 import javax.swing.plaf.*;
  45 import javax.swing.table.*;
  46 import javax.swing.border.*;
  47 
  48 import java.text.NumberFormat;
  49 import java.text.DateFormat;
  50 import java.text.MessageFormat;
  51 
  52 import javax.print.attribute.*;
  53 import javax.print.PrintService;
  54 
  55 import sun.awt.AWTAccessor;
  56 import sun.awt.AWTAccessor.MouseEventAccessor;
  57 import sun.reflect.misc.ReflectUtil;
  58 
  59 import sun.swing.SwingUtilities2;
  60 import sun.swing.SwingUtilities2.Section;
  61 import static sun.swing.SwingUtilities2.Section.*;
  62 import sun.swing.PrintingStatus;
  63 
  64 /**
  65  * The <code>JTable</code> is used to display and edit regular two-dimensional tables
  66  * of cells.
  67  * See <a href="https://docs.oracle.com/javase/tutorial/uiswing/components/table.html">How to Use Tables</a>
  68  * in <em>The Java Tutorial</em>
  69  * for task-oriented documentation and examples of using <code>JTable</code>.
  70  *
  71  * <p>
  72  * The <code>JTable</code> has many
  73  * facilities that make it possible to customize its rendering and editing
  74  * but provides defaults for these features so that simple tables can be
  75  * set up easily.  For example, to set up a table with 10 rows and 10
  76  * columns of numbers:
  77  *
  78  * <pre>
  79  *      TableModel dataModel = new AbstractTableModel() {
  80  *          public int getColumnCount() { return 10; }
  81  *          public int getRowCount() { return 10;}
  82  *          public Object getValueAt(int row, int col) { return new Integer(row*col); }
  83  *      };
  84  *      JTable table = new JTable(dataModel);
  85  *      JScrollPane scrollpane = new JScrollPane(table);
  86  * </pre>
  87  * <p>
  88  * {@code JTable}s are typically placed inside of a {@code JScrollPane}.  By
  89  * default, a {@code JTable} will adjust its width such that
  90  * a horizontal scrollbar is unnecessary.  To allow for a horizontal scrollbar,
  91  * invoke {@link #setAutoResizeMode} with {@code AUTO_RESIZE_OFF}.
  92  * Note that if you wish to use a <code>JTable</code> in a standalone
  93  * view (outside of a <code>JScrollPane</code>) and want the header
  94  * displayed, you can get it using {@link #getTableHeader} and
  95  * display it separately.
  96  * <p>
  97  * To enable sorting and filtering of rows, use a
  98  * {@code RowSorter}.
  99  * You can set up a row sorter in either of two ways:
 100  * <ul>
 101  *   <li>Directly set the {@code RowSorter}. For example:
 102  *        {@code table.setRowSorter(new TableRowSorter(model))}.
 103  *   <li>Set the {@code autoCreateRowSorter}
 104  *       property to {@code true}, so that the {@code JTable}
 105  *       creates a {@code RowSorter} for
 106  *       you. For example: {@code setAutoCreateRowSorter(true)}.
 107  * </ul>
 108  * <p>
 109  * When designing applications that use the <code>JTable</code> it is worth paying
 110  * close attention to the data structures that will represent the table's data.
 111  * The <code>DefaultTableModel</code> is a model implementation that
 112  * uses a <code>Vector</code> of <code>Vector</code>s of <code>Object</code>s to
 113  * store the cell values. As well as copying the data from an
 114  * application into the <code>DefaultTableModel</code>,
 115  * it is also possible to wrap the data in the methods of the
 116  * <code>TableModel</code> interface so that the data can be passed to the
 117  * <code>JTable</code> directly, as in the example above. This often results
 118  * in more efficient applications because the model is free to choose the
 119  * internal representation that best suits the data.
 120  * A good rule of thumb for deciding whether to use the <code>AbstractTableModel</code>
 121  * or the <code>DefaultTableModel</code> is to use the <code>AbstractTableModel</code>
 122  * as the base class for creating subclasses and the <code>DefaultTableModel</code>
 123  * when subclassing is not required.
 124  * <p>
 125  * The "TableExample" directory in the demo area of the source distribution
 126  * gives a number of complete examples of <code>JTable</code> usage,
 127  * covering how the <code>JTable</code> can be used to provide an
 128  * editable view of data taken from a database and how to modify
 129  * the columns in the display to use specialized renderers and editors.
 130  * <p>
 131  * The <code>JTable</code> uses integers exclusively to refer to both the rows and the columns
 132  * of the model that it displays. The <code>JTable</code> simply takes a tabular range of cells
 133  * and uses <code>getValueAt(int, int)</code> to retrieve the
 134  * values from the model during painting.  It is important to remember that
 135  * the column and row indexes returned by various <code>JTable</code> methods
 136  * are in terms of the <code>JTable</code> (the view) and are not
 137  * necessarily the same indexes used by the model.
 138  * <p>
 139  * By default, columns may be rearranged in the <code>JTable</code> so that the
 140  * view's columns appear in a different order to the columns in the model.
 141  * This does not affect the implementation of the model at all: when the
 142  * columns are reordered, the <code>JTable</code> maintains the new order of the columns
 143  * internally and converts its column indices before querying the model.
 144  * <p>
 145  * So, when writing a <code>TableModel</code>, it is not necessary to listen for column
 146  * reordering events as the model will be queried in its own coordinate
 147  * system regardless of what is happening in the view.
 148  * In the examples area there is a demonstration of a sorting algorithm making
 149  * use of exactly this technique to interpose yet another coordinate system
 150  * where the order of the rows is changed, rather than the order of the columns.
 151  * <p>
 152  * Similarly when using the sorting and filtering functionality
 153  * provided by <code>RowSorter</code> the underlying
 154  * <code>TableModel</code> does not need to know how to do sorting,
 155  * rather <code>RowSorter</code> will handle it.  Coordinate
 156  * conversions will be necessary when using the row based methods of
 157  * <code>JTable</code> with the underlying <code>TableModel</code>.
 158  * All of <code>JTable</code>s row based methods are in terms of the
 159  * <code>RowSorter</code>, which is not necessarily the same as that
 160  * of the underlying <code>TableModel</code>.  For example, the
 161  * selection is always in terms of <code>JTable</code> so that when
 162  * using <code>RowSorter</code> you will need to convert using
 163  * <code>convertRowIndexToView</code> or
 164  * <code>convertRowIndexToModel</code>.  The following shows how to
 165  * convert coordinates from <code>JTable</code> to that of the
 166  * underlying model:
 167  * <pre>
 168  *   int[] selection = table.getSelectedRows();
 169  *   for (int i = 0; i &lt; selection.length; i++) {
 170  *     selection[i] = table.convertRowIndexToModel(selection[i]);
 171  *   }
 172  *   // selection is now in terms of the underlying TableModel
 173  * </pre>
 174  * <p>
 175  * By default if sorting is enabled <code>JTable</code> will persist the
 176  * selection and variable row heights in terms of the model on
 177  * sorting.  For example if row 0, in terms of the underlying model,
 178  * is currently selected, after the sort row 0, in terms of the
 179  * underlying model will be selected.  Visually the selection may
 180  * change, but in terms of the underlying model it will remain the
 181  * same.  The one exception to that is if the model index is no longer
 182  * visible or was removed.  For example, if row 0 in terms of model
 183  * was filtered out the selection will be empty after the sort.
 184  * <p>
 185  * J2SE 5 adds methods to <code>JTable</code> to provide convenient access to some
 186  * common printing needs. Simple new {@link #print()} methods allow for quick
 187  * and easy addition of printing support to your application. In addition, a new
 188  * {@link #getPrintable} method is available for more advanced printing needs.
 189  * <p>
 190  * As for all <code>JComponent</code> classes, you can use
 191  * {@link InputMap} and {@link ActionMap} to associate an
 192  * {@link Action} object with a {@link KeyStroke} and execute the
 193  * action under specified conditions.
 194  * <p>
 195  * <strong>Warning:</strong> Swing is not thread safe. For more
 196  * information see <a
 197  * href="package-summary.html#threading">Swing's Threading
 198  * Policy</a>.
 199  * <p>
 200  * <strong>Warning:</strong>
 201  * Serialized objects of this class will not be compatible with
 202  * future Swing releases. The current serialization support is
 203  * appropriate for short term storage or RMI between applications running
 204  * the same version of Swing.  As of 1.4, support for long term storage
 205  * of all JavaBeans&trade;
 206  * has been added to the <code>java.beans</code> package.
 207  * Please see {@link java.beans.XMLEncoder}.
 208  *
 209  *
 210  * @beaninfo
 211  *   attribute: isContainer false
 212  * description: A component which displays data in a two dimensional grid.
 213  *
 214  * @author Philip Milne
 215  * @author Shannon Hickey (printing support)
 216  * @see javax.swing.table.DefaultTableModel
 217  * @see javax.swing.table.TableRowSorter
 218  */
 219 /* The first versions of the JTable, contained in Swing-0.1 through
 220  * Swing-0.4, were written by Alan Chung.
 221  */
 222 public class JTable extends JComponent implements TableModelListener, Scrollable,
 223     TableColumnModelListener, ListSelectionListener, CellEditorListener,
 224     Accessible, RowSorterListener
 225 {
 226 //
 227 // Static Constants
 228 //
 229 
 230     /**
 231      * @see #getUIClassID
 232      * @see #readObject
 233      */
 234     private static final String uiClassID = "TableUI";
 235 
 236     /** Do not adjust column widths automatically; use a horizontal scrollbar instead. */
 237     public static final int     AUTO_RESIZE_OFF = 0;
 238 
 239     /** When a column is adjusted in the UI, adjust the next column the opposite way. */
 240     public static final int     AUTO_RESIZE_NEXT_COLUMN = 1;
 241 
 242     /** During UI adjustment, change subsequent columns to preserve the total width;
 243       * this is the default behavior. */
 244     public static final int     AUTO_RESIZE_SUBSEQUENT_COLUMNS = 2;
 245 
 246     /** During all resize operations, apply adjustments to the last column only. */
 247     public static final int     AUTO_RESIZE_LAST_COLUMN = 3;
 248 
 249     /** During all resize operations, proportionately resize all columns. */
 250     public static final int     AUTO_RESIZE_ALL_COLUMNS = 4;
 251 
 252 
 253     /**
 254      * Printing modes, used in printing <code>JTable</code>s.
 255      *
 256      * @see #print(JTable.PrintMode, MessageFormat, MessageFormat,
 257      *             boolean, PrintRequestAttributeSet, boolean)
 258      * @see #getPrintable
 259      * @since 1.5
 260      */
 261     public enum PrintMode {
 262 
 263         /**
 264          * Printing mode that prints the table at its current size,
 265          * spreading both columns and rows across multiple pages if necessary.
 266          */
 267         NORMAL,
 268 
 269         /**
 270          * Printing mode that scales the output smaller, if necessary,
 271          * to fit the table's entire width (and thereby all columns) on each page;
 272          * Rows are spread across multiple pages as necessary.
 273          */
 274         FIT_WIDTH
 275     }
 276 
 277 
 278 //
 279 // Instance Variables
 280 //
 281 
 282     /** The <code>TableModel</code> of the table. */
 283     protected TableModel        dataModel;
 284 
 285     /** The <code>TableColumnModel</code> of the table. */
 286     protected TableColumnModel  columnModel;
 287 
 288     /** The <code>ListSelectionModel</code> of the table, used to keep track of row selections. */
 289     protected ListSelectionModel selectionModel;
 290 
 291     /** The <code>TableHeader</code> working with the table. */
 292     protected JTableHeader      tableHeader;
 293 
 294     /** The height in pixels of each row in the table. */
 295     protected int               rowHeight;
 296 
 297     /** The height in pixels of the margin between the cells in each row. */
 298     protected int               rowMargin;
 299 
 300     /** The color of the grid. */
 301     protected Color             gridColor;
 302 
 303     /** The table draws horizontal lines between cells if <code>showHorizontalLines</code> is true. */
 304     protected boolean           showHorizontalLines;
 305 
 306     /** The table draws vertical lines between cells if <code>showVerticalLines</code> is true. */
 307     protected boolean           showVerticalLines;
 308 
 309     /**
 310      *  Determines if the table automatically resizes the
 311      *  width of the table's columns to take up the entire width of the
 312      *  table, and how it does the resizing.
 313      */
 314     protected int               autoResizeMode;
 315 
 316     /**
 317      *  The table will query the <code>TableModel</code> to build the default
 318      *  set of columns if this is true.
 319      */
 320     protected boolean           autoCreateColumnsFromModel;
 321 
 322     /** Used by the <code>Scrollable</code> interface to determine the initial visible area. */
 323     protected Dimension         preferredViewportSize;
 324 
 325     /** True if row selection is allowed in this table. */
 326     protected boolean           rowSelectionAllowed;
 327 
 328     /**
 329      * Obsolete as of Java 2 platform v1.3.  Please use the
 330      * <code>rowSelectionAllowed</code> property and the
 331      * <code>columnSelectionAllowed</code> property of the
 332      * <code>columnModel</code> instead. Or use the
 333      * method <code>getCellSelectionEnabled</code>.
 334      */
 335     /*
 336      * If true, both a row selection and a column selection
 337      * can be non-empty at the same time, the selected cells are the
 338      * the cells whose row and column are both selected.
 339      */
 340     protected boolean           cellSelectionEnabled;
 341 
 342     /** If editing, the <code>Component</code> that is handling the editing. */
 343     transient protected Component       editorComp;
 344 
 345     /**
 346      * The active cell editor object, that overwrites the screen real estate
 347      * occupied by the current cell and allows the user to change its contents.
 348      * {@code null} if the table isn't currently editing.
 349      */
 350     transient protected TableCellEditor cellEditor;
 351 
 352     /** Identifies the column of the cell being edited. */
 353     transient protected int             editingColumn;
 354 
 355     /** Identifies the row of the cell being edited. */
 356     transient protected int             editingRow;
 357 
 358     /**
 359      * A table of objects that display the contents of a cell,
 360      * indexed by class as declared in <code>getColumnClass</code>
 361      * in the <code>TableModel</code> interface.
 362      */
 363     transient protected Hashtable defaultRenderersByColumnClass;
 364 
 365     /**
 366      * A table of objects that display and edit the contents of a cell,
 367      * indexed by class as declared in <code>getColumnClass</code>
 368      * in the <code>TableModel</code> interface.
 369      */
 370     transient protected Hashtable defaultEditorsByColumnClass;
 371 
 372     /** The foreground color of selected cells. */
 373     protected Color selectionForeground;
 374 
 375     /** The background color of selected cells. */
 376     protected Color selectionBackground;
 377 
 378 //
 379 // Private state
 380 //
 381 
 382     // WARNING: If you directly access this field you should also change the
 383     // SortManager.modelRowSizes field as well.
 384     private SizeSequence rowModel;
 385     private boolean dragEnabled;
 386     private boolean surrendersFocusOnKeystroke;
 387     private PropertyChangeListener editorRemover = null;
 388     /**
 389      * The last value of getValueIsAdjusting from the column selection models
 390      * columnSelectionChanged notification. Used to test if a repaint is
 391      * needed.
 392      */
 393     private boolean columnSelectionAdjusting;
 394     /**
 395      * The last value of getValueIsAdjusting from the row selection models
 396      * valueChanged notification. Used to test if a repaint is needed.
 397      */
 398     private boolean rowSelectionAdjusting;
 399 
 400     /**
 401      * To communicate errors between threads during printing.
 402      */
 403     private Throwable printError;
 404 
 405     /**
 406      * True when setRowHeight(int) has been invoked.
 407      */
 408     private boolean isRowHeightSet;
 409 
 410     /**
 411      * If true, on a sort the selection is reset.
 412      */
 413     private boolean updateSelectionOnSort;
 414 
 415     /**
 416      * Information used in sorting.
 417      */
 418     private transient SortManager sortManager;
 419 
 420     /**
 421      * If true, when sorterChanged is invoked it's value is ignored.
 422      */
 423     private boolean ignoreSortChange;
 424 
 425     /**
 426      * Whether or not sorterChanged has been invoked.
 427      */
 428     private boolean sorterChanged;
 429 
 430     /**
 431      * If true, any time the model changes a new RowSorter is set.
 432      */
 433     private boolean autoCreateRowSorter;
 434 
 435     /**
 436      * Whether or not the table always fills the viewport height.
 437      * @see #setFillsViewportHeight
 438      * @see #getScrollableTracksViewportHeight
 439      */
 440     private boolean fillsViewportHeight;
 441 
 442     /**
 443      * The drop mode for this component.
 444      */
 445     private DropMode dropMode = DropMode.USE_SELECTION;
 446 
 447     /**
 448      * The drop location.
 449      */
 450     private transient DropLocation dropLocation;
 451 
 452     /**
 453      * A subclass of <code>TransferHandler.DropLocation</code> representing
 454      * a drop location for a <code>JTable</code>.
 455      *
 456      * @see #getDropLocation
 457      * @since 1.6
 458      */
 459     public static final class DropLocation extends TransferHandler.DropLocation {
 460         private final int row;
 461         private final int col;
 462         private final boolean isInsertRow;
 463         private final boolean isInsertCol;
 464 
 465         private DropLocation(Point p, int row, int col,
 466                              boolean isInsertRow, boolean isInsertCol) {
 467 
 468             super(p);
 469             this.row = row;
 470             this.col = col;
 471             this.isInsertRow = isInsertRow;
 472             this.isInsertCol = isInsertCol;
 473         }
 474 
 475         /**
 476          * Returns the row index where a dropped item should be placed in the
 477          * table. Interpretation of the value depends on the return of
 478          * <code>isInsertRow()</code>. If that method returns
 479          * <code>true</code> this value indicates the index where a new
 480          * row should be inserted. Otherwise, it represents the value
 481          * of an existing row on which the data was dropped. This index is
 482          * in terms of the view.
 483          * <p>
 484          * <code>-1</code> indicates that the drop occurred over empty space,
 485          * and no row could be calculated.
 486          *
 487          * @return the drop row
 488          */
 489         public int getRow() {
 490             return row;
 491         }
 492 
 493         /**
 494          * Returns the column index where a dropped item should be placed in the
 495          * table. Interpretation of the value depends on the return of
 496          * <code>isInsertColumn()</code>. If that method returns
 497          * <code>true</code> this value indicates the index where a new
 498          * column should be inserted. Otherwise, it represents the value
 499          * of an existing column on which the data was dropped. This index is
 500          * in terms of the view.
 501          * <p>
 502          * <code>-1</code> indicates that the drop occurred over empty space,
 503          * and no column could be calculated.
 504          *
 505          * @return the drop row
 506          */
 507         public int getColumn() {
 508             return col;
 509         }
 510 
 511         /**
 512          * Returns whether or not this location represents an insert
 513          * of a row.
 514          *
 515          * @return whether or not this is an insert row
 516          */
 517         public boolean isInsertRow() {
 518             return isInsertRow;
 519         }
 520 
 521         /**
 522          * Returns whether or not this location represents an insert
 523          * of a column.
 524          *
 525          * @return whether or not this is an insert column
 526          */
 527         public boolean isInsertColumn() {
 528             return isInsertCol;
 529         }
 530 
 531         /**
 532          * Returns a string representation of this drop location.
 533          * This method is intended to be used for debugging purposes,
 534          * and the content and format of the returned string may vary
 535          * between implementations.
 536          *
 537          * @return a string representation of this drop location
 538          */
 539         public String toString() {
 540             return getClass().getName()
 541                    + "[dropPoint=" + getDropPoint() + ","
 542                    + "row=" + row + ","
 543                    + "column=" + col + ","
 544                    + "insertRow=" + isInsertRow + ","
 545                    + "insertColumn=" + isInsertCol + "]";
 546         }
 547     }
 548 
 549 //
 550 // Constructors
 551 //
 552 
 553     /**
 554      * Constructs a default <code>JTable</code> that is initialized with a default
 555      * data model, a default column model, and a default selection
 556      * model.
 557      *
 558      * @see #createDefaultDataModel
 559      * @see #createDefaultColumnModel
 560      * @see #createDefaultSelectionModel
 561      */
 562     public JTable() {
 563         this(null, null, null);
 564     }
 565 
 566     /**
 567      * Constructs a <code>JTable</code> that is initialized with
 568      * <code>dm</code> as the data model, a default column model,
 569      * and a default selection model.
 570      *
 571      * @param dm        the data model for the table
 572      * @see #createDefaultColumnModel
 573      * @see #createDefaultSelectionModel
 574      */
 575     public JTable(TableModel dm) {
 576         this(dm, null, null);
 577     }
 578 
 579     /**
 580      * Constructs a <code>JTable</code> that is initialized with
 581      * <code>dm</code> as the data model, <code>cm</code>
 582      * as the column model, and a default selection model.
 583      *
 584      * @param dm        the data model for the table
 585      * @param cm        the column model for the table
 586      * @see #createDefaultSelectionModel
 587      */
 588     public JTable(TableModel dm, TableColumnModel cm) {
 589         this(dm, cm, null);
 590     }
 591 
 592     /**
 593      * Constructs a <code>JTable</code> that is initialized with
 594      * <code>dm</code> as the data model, <code>cm</code> as the
 595      * column model, and <code>sm</code> as the selection model.
 596      * If any of the parameters are <code>null</code> this method
 597      * will initialize the table with the corresponding default model.
 598      * The <code>autoCreateColumnsFromModel</code> flag is set to false
 599      * if <code>cm</code> is non-null, otherwise it is set to true
 600      * and the column model is populated with suitable
 601      * <code>TableColumns</code> for the columns in <code>dm</code>.
 602      *
 603      * @param dm        the data model for the table
 604      * @param cm        the column model for the table
 605      * @param sm        the row selection model for the table
 606      * @see #createDefaultDataModel
 607      * @see #createDefaultColumnModel
 608      * @see #createDefaultSelectionModel
 609      */
 610     public JTable(TableModel dm, TableColumnModel cm, ListSelectionModel sm) {
 611         super();
 612         setLayout(null);
 613 
 614         setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
 615                            JComponent.getManagingFocusForwardTraversalKeys());
 616         setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,
 617                            JComponent.getManagingFocusBackwardTraversalKeys());
 618         if (cm == null) {
 619             cm = createDefaultColumnModel();
 620             autoCreateColumnsFromModel = true;
 621         }
 622         setColumnModel(cm);
 623 
 624         if (sm == null) {
 625             sm = createDefaultSelectionModel();
 626         }
 627         setSelectionModel(sm);
 628 
 629     // Set the model last, that way if the autoCreatColumnsFromModel has
 630     // been set above, we will automatically populate an empty columnModel
 631     // with suitable columns for the new model.
 632         if (dm == null) {
 633             dm = createDefaultDataModel();
 634         }
 635         setModel(dm);
 636 
 637         initializeLocalVars();
 638         updateUI();
 639     }
 640 
 641     /**
 642      * Constructs a <code>JTable</code> with <code>numRows</code>
 643      * and <code>numColumns</code> of empty cells using
 644      * <code>DefaultTableModel</code>.  The columns will have
 645      * names of the form "A", "B", "C", etc.
 646      *
 647      * @param numRows           the number of rows the table holds
 648      * @param numColumns        the number of columns the table holds
 649      * @see javax.swing.table.DefaultTableModel
 650      */
 651     public JTable(int numRows, int numColumns) {
 652         this(new DefaultTableModel(numRows, numColumns));
 653     }
 654 
 655     /**
 656      * Constructs a <code>JTable</code> to display the values in the
 657      * <code>Vector</code> of <code>Vectors</code>, <code>rowData</code>,
 658      * with column names, <code>columnNames</code>.  The
 659      * <code>Vectors</code> contained in <code>rowData</code>
 660      * should contain the values for that row. In other words,
 661      * the value of the cell at row 1, column 5 can be obtained
 662      * with the following code:
 663      *
 664      * <pre>((Vector)rowData.elementAt(1)).elementAt(5);</pre>
 665      * <p>
 666      * @param rowData           the data for the new table
 667      * @param columnNames       names of each column
 668      */
 669     public JTable(Vector rowData, Vector columnNames) {
 670         this(new DefaultTableModel(rowData, columnNames));
 671     }
 672 
 673     /**
 674      * Constructs a <code>JTable</code> to display the values in the two dimensional array,
 675      * <code>rowData</code>, with column names, <code>columnNames</code>.
 676      * <code>rowData</code> is an array of rows, so the value of the cell at row 1,
 677      * column 5 can be obtained with the following code:
 678      *
 679      * <pre> rowData[1][5]; </pre>
 680      * <p>
 681      * All rows must be of the same length as <code>columnNames</code>.
 682      * <p>
 683      * @param rowData           the data for the new table
 684      * @param columnNames       names of each column
 685      */
 686     public JTable(final Object[][] rowData, final Object[] columnNames) {
 687         this(new AbstractTableModel() {
 688             public String getColumnName(int column) { return columnNames[column].toString(); }
 689             public int getRowCount() { return rowData.length; }
 690             public int getColumnCount() { return columnNames.length; }
 691             public Object getValueAt(int row, int col) { return rowData[row][col]; }
 692             public boolean isCellEditable(int row, int column) { return true; }
 693             public void setValueAt(Object value, int row, int col) {
 694                 rowData[row][col] = value;
 695                 fireTableCellUpdated(row, col);
 696             }
 697         });
 698     }
 699 
 700     /**
 701      * Calls the <code>configureEnclosingScrollPane</code> method.
 702      *
 703      * @see #configureEnclosingScrollPane
 704      */
 705     public void addNotify() {
 706         super.addNotify();
 707         configureEnclosingScrollPane();
 708     }
 709 
 710     /**
 711      * If this <code>JTable</code> is the <code>viewportView</code> of an enclosing <code>JScrollPane</code>
 712      * (the usual situation), configure this <code>ScrollPane</code> by, amongst other things,
 713      * installing the table's <code>tableHeader</code> as the <code>columnHeaderView</code> of the scroll pane.
 714      * When a <code>JTable</code> is added to a <code>JScrollPane</code> in the usual way,
 715      * using <code>new JScrollPane(myTable)</code>, <code>addNotify</code> is
 716      * called in the <code>JTable</code> (when the table is added to the viewport).
 717      * <code>JTable</code>'s <code>addNotify</code> method in turn calls this method,
 718      * which is protected so that this default installation procedure can
 719      * be overridden by a subclass.
 720      *
 721      * @see #addNotify
 722      */
 723     protected void configureEnclosingScrollPane() {
 724         Container parent = SwingUtilities.getUnwrappedParent(this);
 725         if (parent instanceof JViewport) {
 726             JViewport port = (JViewport) parent;
 727             Container gp = port.getParent();
 728             if (gp instanceof JScrollPane) {
 729                 JScrollPane scrollPane = (JScrollPane)gp;
 730                 // Make certain we are the viewPort's view and not, for
 731                 // example, the rowHeaderView of the scrollPane -
 732                 // an implementor of fixed columns might do this.
 733                 JViewport viewport = scrollPane.getViewport();
 734                 if (viewport == null ||
 735                         SwingUtilities.getUnwrappedView(viewport) != this) {
 736                     return;
 737                 }
 738                 scrollPane.setColumnHeaderView(getTableHeader());
 739                 // configure the scrollpane for any LAF dependent settings
 740                 configureEnclosingScrollPaneUI();
 741             }
 742         }
 743     }
 744 
 745     /**
 746      * This is a sub-part of configureEnclosingScrollPane() that configures
 747      * anything on the scrollpane that may change when the look and feel
 748      * changes. It needed to be split out from configureEnclosingScrollPane() so
 749      * that it can be called from updateUI() when the LAF changes without
 750      * causing the regression found in bug 6687962. This was because updateUI()
 751      * is called from the constructor which then caused
 752      * configureEnclosingScrollPane() to be called by the constructor which
 753      * changes its contract for any subclass that overrides it. So by splitting
 754      * it out in this way configureEnclosingScrollPaneUI() can be called both
 755      * from configureEnclosingScrollPane() and updateUI() in a safe manor.
 756      */
 757     private void configureEnclosingScrollPaneUI() {
 758         Container parent = SwingUtilities.getUnwrappedParent(this);
 759         if (parent instanceof JViewport) {
 760             JViewport port = (JViewport) parent;
 761             Container gp = port.getParent();
 762             if (gp instanceof JScrollPane) {
 763                 JScrollPane scrollPane = (JScrollPane)gp;
 764                 // Make certain we are the viewPort's view and not, for
 765                 // example, the rowHeaderView of the scrollPane -
 766                 // an implementor of fixed columns might do this.
 767                 JViewport viewport = scrollPane.getViewport();
 768                 if (viewport == null ||
 769                         SwingUtilities.getUnwrappedView(viewport) != this) {
 770                     return;
 771                 }
 772                 //  scrollPane.getViewport().setBackingStoreEnabled(true);
 773                 Border border = scrollPane.getBorder();
 774                 if (border == null || border instanceof UIResource) {
 775                     Border scrollPaneBorder =
 776                         UIManager.getBorder("Table.scrollPaneBorder");
 777                     if (scrollPaneBorder != null) {
 778                         scrollPane.setBorder(scrollPaneBorder);
 779                     }
 780                 }
 781                 // add JScrollBar corner component if available from LAF and not already set by the user
 782                 Component corner =
 783                         scrollPane.getCorner(JScrollPane.UPPER_TRAILING_CORNER);
 784                 if (corner == null || corner instanceof UIResource){
 785                     corner = null;
 786                     try {
 787                         corner = (Component) UIManager.get(
 788                                 "Table.scrollPaneCornerComponent");
 789                     } catch (Exception e) {
 790                         // just ignore and don't set corner
 791                     }
 792                     scrollPane.setCorner(JScrollPane.UPPER_TRAILING_CORNER,
 793                             corner);
 794                 }
 795             }
 796         }
 797     }
 798 
 799     /**
 800      * Calls the <code>unconfigureEnclosingScrollPane</code> method.
 801      *
 802      * @see #unconfigureEnclosingScrollPane
 803      */
 804     public void removeNotify() {
 805         KeyboardFocusManager.getCurrentKeyboardFocusManager().
 806             removePropertyChangeListener("permanentFocusOwner", editorRemover);
 807         editorRemover = null;
 808         unconfigureEnclosingScrollPane();
 809         super.removeNotify();
 810     }
 811 
 812     /**
 813      * Reverses the effect of <code>configureEnclosingScrollPane</code>
 814      * by replacing the <code>columnHeaderView</code> of the enclosing
 815      * scroll pane with <code>null</code>. <code>JTable</code>'s
 816      * <code>removeNotify</code> method calls
 817      * this method, which is protected so that this default uninstallation
 818      * procedure can be overridden by a subclass.
 819      *
 820      * @see #removeNotify
 821      * @see #configureEnclosingScrollPane
 822      * @since 1.3
 823      */
 824     protected void unconfigureEnclosingScrollPane() {
 825         Container parent = SwingUtilities.getUnwrappedParent(this);
 826         if (parent instanceof JViewport) {
 827             JViewport port = (JViewport) parent;
 828             Container gp = port.getParent();
 829             if (gp instanceof JScrollPane) {
 830                 JScrollPane scrollPane = (JScrollPane)gp;
 831                 // Make certain we are the viewPort's view and not, for
 832                 // example, the rowHeaderView of the scrollPane -
 833                 // an implementor of fixed columns might do this.
 834                 JViewport viewport = scrollPane.getViewport();
 835                 if (viewport == null ||
 836                         SwingUtilities.getUnwrappedView(viewport) != this) {
 837                     return;
 838                 }
 839                 scrollPane.setColumnHeaderView(null);
 840                 // remove ScrollPane corner if one was added by the LAF
 841                 Component corner =
 842                         scrollPane.getCorner(JScrollPane.UPPER_TRAILING_CORNER);
 843                 if (corner instanceof UIResource){
 844                     scrollPane.setCorner(JScrollPane.UPPER_TRAILING_CORNER,
 845                             null);
 846                 }
 847             }
 848         }
 849     }
 850 
 851     void setUIProperty(String propertyName, Object value) {
 852         if (propertyName == "rowHeight") {
 853             if (!isRowHeightSet) {
 854                 setRowHeight(((Number)value).intValue());
 855                 isRowHeightSet = false;
 856             }
 857             return;
 858         }
 859         super.setUIProperty(propertyName, value);
 860     }
 861 
 862 //
 863 // Static Methods
 864 //
 865 
 866     /**
 867      * Equivalent to <code>new JScrollPane(aTable)</code>.
 868      *
 869      * @deprecated As of Swing version 1.0.2,
 870      * replaced by <code>new JScrollPane(aTable)</code>.
 871      */
 872     @Deprecated
 873     static public JScrollPane createScrollPaneForTable(JTable aTable) {
 874         return new JScrollPane(aTable);
 875     }
 876 
 877 //
 878 // Table Attributes
 879 //
 880 
 881     /**
 882      * Sets the <code>tableHeader</code> working with this <code>JTable</code> to <code>newHeader</code>.
 883      * It is legal to have a <code>null</code> <code>tableHeader</code>.
 884      *
 885      * @param   tableHeader                       new tableHeader
 886      * @see     #getTableHeader
 887      * @beaninfo
 888      *  bound: true
 889      *  description: The JTableHeader instance which renders the column headers.
 890      */
 891     public void setTableHeader(JTableHeader tableHeader) {
 892         if (this.tableHeader != tableHeader) {
 893             JTableHeader old = this.tableHeader;
 894             // Release the old header
 895             if (old != null) {
 896                 old.setTable(null);
 897             }
 898             this.tableHeader = tableHeader;
 899             if (tableHeader != null) {
 900                 tableHeader.setTable(this);
 901             }
 902             firePropertyChange("tableHeader", old, tableHeader);
 903         }
 904     }
 905 
 906     /**
 907      * Returns the <code>tableHeader</code> used by this <code>JTable</code>.
 908      *
 909      * @return  the <code>tableHeader</code> used by this table
 910      * @see     #setTableHeader
 911      */
 912     public JTableHeader getTableHeader() {
 913         return tableHeader;
 914     }
 915 
 916     /**
 917      * Sets the height, in pixels, of all cells to <code>rowHeight</code>,
 918      * revalidates, and repaints.
 919      * The height of the cells will be equal to the row height minus
 920      * the row margin.
 921      *
 922      * @param   rowHeight                       new row height
 923      * @exception IllegalArgumentException      if <code>rowHeight</code> is
 924      *                                          less than 1
 925      * @see     #getRowHeight
 926      * @beaninfo
 927      *  bound: true
 928      *  description: The height of the specified row.
 929      */
 930     public void setRowHeight(int rowHeight) {
 931         if (rowHeight <= 0) {
 932             throw new IllegalArgumentException("New row height less than 1");
 933         }
 934         int old = this.rowHeight;
 935         this.rowHeight = rowHeight;
 936         rowModel = null;
 937         if (sortManager != null) {
 938             sortManager.modelRowSizes = null;
 939         }
 940         isRowHeightSet = true;
 941         resizeAndRepaint();
 942         firePropertyChange("rowHeight", old, rowHeight);
 943     }
 944 
 945     /**
 946      * Returns the height of a table row, in pixels.
 947      *
 948      * @return  the height in pixels of a table row
 949      * @see     #setRowHeight
 950      */
 951     public int getRowHeight() {
 952         return rowHeight;
 953     }
 954 
 955     private SizeSequence getRowModel() {
 956         if (rowModel == null) {
 957             rowModel = new SizeSequence(getRowCount(), getRowHeight());
 958         }
 959         return rowModel;
 960     }
 961 
 962     /**
 963      * Sets the height for <code>row</code> to <code>rowHeight</code>,
 964      * revalidates, and repaints. The height of the cells in this row
 965      * will be equal to the row height minus the row margin.
 966      *
 967      * @param   row                             the row whose height is being
 968                                                 changed
 969      * @param   rowHeight                       new row height, in pixels
 970      * @exception IllegalArgumentException      if <code>rowHeight</code> is
 971      *                                          less than 1
 972      * @beaninfo
 973      *  bound: true
 974      *  description: The height in pixels of the cells in <code>row</code>
 975      * @since 1.3
 976      */
 977     public void setRowHeight(int row, int rowHeight) {
 978         if (rowHeight <= 0) {
 979             throw new IllegalArgumentException("New row height less than 1");
 980         }
 981         getRowModel().setSize(row, rowHeight);
 982         if (sortManager != null) {
 983             sortManager.setViewRowHeight(row, rowHeight);
 984         }
 985         resizeAndRepaint();
 986     }
 987 
 988     /**
 989      * Returns the height, in pixels, of the cells in <code>row</code>.
 990      * @param   row              the row whose height is to be returned
 991      * @return the height, in pixels, of the cells in the row
 992      * @since 1.3
 993      */
 994     public int getRowHeight(int row) {
 995         return (rowModel == null) ? getRowHeight() : rowModel.getSize(row);
 996     }
 997 
 998     /**
 999      * Sets the amount of empty space between cells in adjacent rows.
1000      *
1001      * @param  rowMargin  the number of pixels between cells in a row
1002      * @see     #getRowMargin
1003      * @beaninfo
1004      *  bound: true
1005      *  description: The amount of space between cells.
1006      */
1007     public void setRowMargin(int rowMargin) {
1008         int old = this.rowMargin;
1009         this.rowMargin = rowMargin;
1010         resizeAndRepaint();
1011         firePropertyChange("rowMargin", old, rowMargin);
1012     }
1013 
1014     /**
1015      * Gets the amount of empty space, in pixels, between cells. Equivalent to:
1016      * <code>getIntercellSpacing().height</code>.
1017      * @return the number of pixels between cells in a row
1018      *
1019      * @see     #setRowMargin
1020      */
1021     public int getRowMargin() {
1022         return rowMargin;
1023     }
1024 
1025     /**
1026      * Sets the <code>rowMargin</code> and the <code>columnMargin</code> --
1027      * the height and width of the space between cells -- to
1028      * <code>intercellSpacing</code>.
1029      *
1030      * @param   intercellSpacing        a <code>Dimension</code>
1031      *                                  specifying the new width
1032      *                                  and height between cells
1033      * @see     #getIntercellSpacing
1034      * @beaninfo
1035      *  description: The spacing between the cells,
1036      *               drawn in the background color of the JTable.
1037      */
1038     public void setIntercellSpacing(Dimension intercellSpacing) {
1039         // Set the rowMargin here and columnMargin in the TableColumnModel
1040         setRowMargin(intercellSpacing.height);
1041         getColumnModel().setColumnMargin(intercellSpacing.width);
1042 
1043         resizeAndRepaint();
1044     }
1045 
1046     /**
1047      * Returns the horizontal and vertical space between cells.
1048      * The default spacing is look and feel dependent.
1049      *
1050      * @return  the horizontal and vertical spacing between cells
1051      * @see     #setIntercellSpacing
1052      */
1053     public Dimension getIntercellSpacing() {
1054         return new Dimension(getColumnModel().getColumnMargin(), rowMargin);
1055     }
1056 
1057     /**
1058      * Sets the color used to draw grid lines to <code>gridColor</code> and redisplays.
1059      * The default color is look and feel dependent.
1060      *
1061      * @param   gridColor                       the new color of the grid lines
1062      * @exception IllegalArgumentException      if <code>gridColor</code> is <code>null</code>
1063      * @see     #getGridColor
1064      * @beaninfo
1065      *  bound: true
1066      *  description: The grid color.
1067      */
1068     public void setGridColor(Color gridColor) {
1069         if (gridColor == null) {
1070             throw new IllegalArgumentException("New color is null");
1071         }
1072         Color old = this.gridColor;
1073         this.gridColor = gridColor;
1074         firePropertyChange("gridColor", old, gridColor);
1075         // Redraw
1076         repaint();
1077     }
1078 
1079     /**
1080      * Returns the color used to draw grid lines.
1081      * The default color is look and feel dependent.
1082      *
1083      * @return  the color used to draw grid lines
1084      * @see     #setGridColor
1085      */
1086     public Color getGridColor() {
1087         return gridColor;
1088     }
1089 
1090     /**
1091      *  Sets whether the table draws grid lines around cells.
1092      *  If <code>showGrid</code> is true it does; if it is false it doesn't.
1093      *  There is no <code>getShowGrid</code> method as this state is held
1094      *  in two variables -- <code>showHorizontalLines</code> and <code>showVerticalLines</code> --
1095      *  each of which can be queried independently.
1096      *
1097      * @param   showGrid                 true if table view should draw grid lines
1098      *
1099      * @see     #setShowVerticalLines
1100      * @see     #setShowHorizontalLines
1101      * @beaninfo
1102      *  description: The color used to draw the grid lines.
1103      */
1104     public void setShowGrid(boolean showGrid) {
1105         setShowHorizontalLines(showGrid);
1106         setShowVerticalLines(showGrid);
1107 
1108         // Redraw
1109         repaint();
1110     }
1111 
1112     /**
1113      *  Sets whether the table draws horizontal lines between cells.
1114      *  If <code>showHorizontalLines</code> is true it does; if it is false it doesn't.
1115      *
1116      * @param   showHorizontalLines      true if table view should draw horizontal lines
1117      * @see     #getShowHorizontalLines
1118      * @see     #setShowGrid
1119      * @see     #setShowVerticalLines
1120      * @beaninfo
1121      *  bound: true
1122      *  description: Whether horizontal lines should be drawn in between the cells.
1123      */
1124     public void setShowHorizontalLines(boolean showHorizontalLines) {
1125         boolean old = this.showHorizontalLines;
1126         this.showHorizontalLines = showHorizontalLines;
1127         firePropertyChange("showHorizontalLines", old, showHorizontalLines);
1128 
1129         // Redraw
1130         repaint();
1131     }
1132 
1133     /**
1134      *  Sets whether the table draws vertical lines between cells.
1135      *  If <code>showVerticalLines</code> is true it does; if it is false it doesn't.
1136      *
1137      * @param   showVerticalLines              true if table view should draw vertical lines
1138      * @see     #getShowVerticalLines
1139      * @see     #setShowGrid
1140      * @see     #setShowHorizontalLines
1141      * @beaninfo
1142      *  bound: true
1143      *  description: Whether vertical lines should be drawn in between the cells.
1144      */
1145     public void setShowVerticalLines(boolean showVerticalLines) {
1146         boolean old = this.showVerticalLines;
1147         this.showVerticalLines = showVerticalLines;
1148         firePropertyChange("showVerticalLines", old, showVerticalLines);
1149         // Redraw
1150         repaint();
1151     }
1152 
1153     /**
1154      * Returns true if the table draws horizontal lines between cells, false if it
1155      * doesn't. The default value is look and feel dependent.
1156      *
1157      * @return  true if the table draws horizontal lines between cells, false if it
1158      *          doesn't
1159      * @see     #setShowHorizontalLines
1160      */
1161     public boolean getShowHorizontalLines() {
1162         return showHorizontalLines;
1163     }
1164 
1165     /**
1166      * Returns true if the table draws vertical lines between cells, false if it
1167      * doesn't. The default value is look and feel dependent.
1168      *
1169      * @return  true if the table draws vertical lines between cells, false if it
1170      *          doesn't
1171      * @see     #setShowVerticalLines
1172      */
1173     public boolean getShowVerticalLines() {
1174         return showVerticalLines;
1175     }
1176 
1177     /**
1178      * Sets the table's auto resize mode when the table is resized.  For further
1179      * information on how the different resize modes work, see
1180      * {@link #doLayout}.
1181      *
1182      * @param   mode One of 5 legal values:
1183      *                   AUTO_RESIZE_OFF,
1184      *                   AUTO_RESIZE_NEXT_COLUMN,
1185      *                   AUTO_RESIZE_SUBSEQUENT_COLUMNS,
1186      *                   AUTO_RESIZE_LAST_COLUMN,
1187      *                   AUTO_RESIZE_ALL_COLUMNS
1188      *
1189      * @see     #getAutoResizeMode
1190      * @see     #doLayout
1191      * @beaninfo
1192      *  bound: true
1193      *  description: Whether the columns should adjust themselves automatically.
1194      *        enum: AUTO_RESIZE_OFF                JTable.AUTO_RESIZE_OFF
1195      *              AUTO_RESIZE_NEXT_COLUMN        JTable.AUTO_RESIZE_NEXT_COLUMN
1196      *              AUTO_RESIZE_SUBSEQUENT_COLUMNS JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS
1197      *              AUTO_RESIZE_LAST_COLUMN        JTable.AUTO_RESIZE_LAST_COLUMN
1198      *              AUTO_RESIZE_ALL_COLUMNS        JTable.AUTO_RESIZE_ALL_COLUMNS
1199      */
1200     public void setAutoResizeMode(int mode) {
1201         if ((mode == AUTO_RESIZE_OFF) ||
1202             (mode == AUTO_RESIZE_NEXT_COLUMN) ||
1203             (mode == AUTO_RESIZE_SUBSEQUENT_COLUMNS) ||
1204             (mode == AUTO_RESIZE_LAST_COLUMN) ||
1205             (mode == AUTO_RESIZE_ALL_COLUMNS)) {
1206             int old = autoResizeMode;
1207             autoResizeMode = mode;
1208             resizeAndRepaint();
1209             if (tableHeader != null) {
1210                 tableHeader.resizeAndRepaint();
1211             }
1212             firePropertyChange("autoResizeMode", old, autoResizeMode);
1213         }
1214     }
1215 
1216     /**
1217      * Returns the auto resize mode of the table.  The default mode
1218      * is AUTO_RESIZE_SUBSEQUENT_COLUMNS.
1219      *
1220      * @return  the autoResizeMode of the table
1221      *
1222      * @see     #setAutoResizeMode
1223      * @see     #doLayout
1224      */
1225     public int getAutoResizeMode() {
1226         return autoResizeMode;
1227     }
1228 
1229     /**
1230      * Sets this table's <code>autoCreateColumnsFromModel</code> flag.
1231      * This method calls <code>createDefaultColumnsFromModel</code> if
1232      * <code>autoCreateColumnsFromModel</code> changes from false to true.
1233      *
1234      * @param   autoCreateColumnsFromModel   true if <code>JTable</code> should automatically create columns
1235      * @see     #getAutoCreateColumnsFromModel
1236      * @see     #createDefaultColumnsFromModel
1237      * @beaninfo
1238      *  bound: true
1239      *  description: Automatically populates the columnModel when a new TableModel is submitted.
1240      */
1241     public void setAutoCreateColumnsFromModel(boolean autoCreateColumnsFromModel) {
1242         if (this.autoCreateColumnsFromModel != autoCreateColumnsFromModel) {
1243             boolean old = this.autoCreateColumnsFromModel;
1244             this.autoCreateColumnsFromModel = autoCreateColumnsFromModel;
1245             if (autoCreateColumnsFromModel) {
1246                 createDefaultColumnsFromModel();
1247             }
1248             firePropertyChange("autoCreateColumnsFromModel", old, autoCreateColumnsFromModel);
1249         }
1250     }
1251 
1252     /**
1253      * Determines whether the table will create default columns from the model.
1254      * If true, <code>setModel</code> will clear any existing columns and
1255      * create new columns from the new model.  Also, if the event in
1256      * the <code>tableChanged</code> notification specifies that the
1257      * entire table changed, then the columns will be rebuilt.
1258      * The default is true.
1259      *
1260      * @return  the autoCreateColumnsFromModel of the table
1261      * @see     #setAutoCreateColumnsFromModel
1262      * @see     #createDefaultColumnsFromModel
1263      */
1264     public boolean getAutoCreateColumnsFromModel() {
1265         return autoCreateColumnsFromModel;
1266     }
1267 
1268     /**
1269      * Creates default columns for the table from
1270      * the data model using the <code>getColumnCount</code> method
1271      * defined in the <code>TableModel</code> interface.
1272      * <p>
1273      * Clears any existing columns before creating the
1274      * new columns based on information from the model.
1275      *
1276      * @see     #getAutoCreateColumnsFromModel
1277      */
1278     public void createDefaultColumnsFromModel() {
1279         TableModel m = getModel();
1280         if (m != null) {
1281             // Remove any current columns
1282             TableColumnModel cm = getColumnModel();
1283             while (cm.getColumnCount() > 0) {
1284                 cm.removeColumn(cm.getColumn(0));
1285             }
1286 
1287             // Create new columns from the data model info
1288             for (int i = 0; i < m.getColumnCount(); i++) {
1289                 TableColumn newColumn = new TableColumn(i);
1290                 addColumn(newColumn);
1291             }
1292         }
1293     }
1294 
1295     /**
1296      * Sets a default cell renderer to be used if no renderer has been set in
1297      * a <code>TableColumn</code>. If renderer is <code>null</code>,
1298      * removes the default renderer for this column class.
1299      *
1300      * @param  columnClass     set the default cell renderer for this columnClass
1301      * @param  renderer        default cell renderer to be used for this
1302      *                         columnClass
1303      * @see     #getDefaultRenderer
1304      * @see     #setDefaultEditor
1305      */
1306     public void setDefaultRenderer(Class<?> columnClass, TableCellRenderer renderer) {
1307         if (renderer != null) {
1308             defaultRenderersByColumnClass.put(columnClass, renderer);
1309         }
1310         else {
1311             defaultRenderersByColumnClass.remove(columnClass);
1312         }
1313     }
1314 
1315     /**
1316      * Returns the cell renderer to be used when no renderer has been set in
1317      * a <code>TableColumn</code>. During the rendering of cells the renderer is fetched from
1318      * a <code>Hashtable</code> of entries according to the class of the cells in the column. If
1319      * there is no entry for this <code>columnClass</code> the method returns
1320      * the entry for the most specific superclass. The <code>JTable</code> installs entries
1321      * for <code>Object</code>, <code>Number</code>, and <code>Boolean</code>, all of which can be modified
1322      * or replaced.
1323      *
1324      * @param   columnClass   return the default cell renderer
1325      *                        for this columnClass
1326      * @return  the renderer for this columnClass
1327      * @see     #setDefaultRenderer
1328      * @see     #getColumnClass
1329      */
1330     public TableCellRenderer getDefaultRenderer(Class<?> columnClass) {
1331         if (columnClass == null) {
1332             return null;
1333         }
1334         else {
1335             Object renderer = defaultRenderersByColumnClass.get(columnClass);
1336             if (renderer != null) {
1337                 return (TableCellRenderer)renderer;
1338             }
1339             else {
1340                 Class c = columnClass.getSuperclass();
1341                 if (c == null && columnClass != Object.class) {
1342                     c = Object.class;
1343                 }
1344                 return getDefaultRenderer(c);
1345             }
1346         }
1347     }
1348 
1349     /**
1350      * Sets a default cell editor to be used if no editor has been set in
1351      * a <code>TableColumn</code>. If no editing is required in a table, or a
1352      * particular column in a table, uses the <code>isCellEditable</code>
1353      * method in the <code>TableModel</code> interface to ensure that this
1354      * <code>JTable</code> will not start an editor in these columns.
1355      * If editor is <code>null</code>, removes the default editor for this
1356      * column class.
1357      *
1358      * @param  columnClass  set the default cell editor for this columnClass
1359      * @param  editor   default cell editor to be used for this columnClass
1360      * @see     TableModel#isCellEditable
1361      * @see     #getDefaultEditor
1362      * @see     #setDefaultRenderer
1363      */
1364     public void setDefaultEditor(Class<?> columnClass, TableCellEditor editor) {
1365         if (editor != null) {
1366             defaultEditorsByColumnClass.put(columnClass, editor);
1367         }
1368         else {
1369             defaultEditorsByColumnClass.remove(columnClass);
1370         }
1371     }
1372 
1373     /**
1374      * Returns the editor to be used when no editor has been set in
1375      * a <code>TableColumn</code>. During the editing of cells the editor is fetched from
1376      * a <code>Hashtable</code> of entries according to the class of the cells in the column. If
1377      * there is no entry for this <code>columnClass</code> the method returns
1378      * the entry for the most specific superclass. The <code>JTable</code> installs entries
1379      * for <code>Object</code>, <code>Number</code>, and <code>Boolean</code>, all of which can be modified
1380      * or replaced.
1381      *
1382      * @param   columnClass  return the default cell editor for this columnClass
1383      * @return the default cell editor to be used for this columnClass
1384      * @see     #setDefaultEditor
1385      * @see     #getColumnClass
1386      */
1387     public TableCellEditor getDefaultEditor(Class<?> columnClass) {
1388         if (columnClass == null) {
1389             return null;
1390         }
1391         else {
1392             Object editor = defaultEditorsByColumnClass.get(columnClass);
1393             if (editor != null) {
1394                 return (TableCellEditor)editor;
1395             }
1396             else {
1397                 return getDefaultEditor(columnClass.getSuperclass());
1398             }
1399         }
1400     }
1401 
1402     /**
1403      * Turns on or off automatic drag handling. In order to enable automatic
1404      * drag handling, this property should be set to {@code true}, and the
1405      * table's {@code TransferHandler} needs to be {@code non-null}.
1406      * The default value of the {@code dragEnabled} property is {@code false}.
1407      * <p>
1408      * The job of honoring this property, and recognizing a user drag gesture,
1409      * lies with the look and feel implementation, and in particular, the table's
1410      * {@code TableUI}. When automatic drag handling is enabled, most look and
1411      * feels (including those that subclass {@code BasicLookAndFeel}) begin a
1412      * drag and drop operation whenever the user presses the mouse button over
1413      * an item (in single selection mode) or a selection (in other selection
1414      * modes) and then moves the mouse a few pixels. Setting this property to
1415      * {@code true} can therefore have a subtle effect on how selections behave.
1416      * <p>
1417      * If a look and feel is used that ignores this property, you can still
1418      * begin a drag and drop operation by calling {@code exportAsDrag} on the
1419      * table's {@code TransferHandler}.
1420      *
1421      * @param b whether or not to enable automatic drag handling
1422      * @exception HeadlessException if
1423      *            <code>b</code> is <code>true</code> and
1424      *            <code>GraphicsEnvironment.isHeadless()</code>
1425      *            returns <code>true</code>
1426      * @see java.awt.GraphicsEnvironment#isHeadless
1427      * @see #getDragEnabled
1428      * @see #setTransferHandler
1429      * @see TransferHandler
1430      * @since 1.4
1431      *
1432      * @beaninfo
1433      *  description: determines whether automatic drag handling is enabled
1434      *        bound: false
1435      */
1436     public void setDragEnabled(boolean b) {
1437         if (b && GraphicsEnvironment.isHeadless()) {
1438             throw new HeadlessException();
1439         }
1440         dragEnabled = b;
1441     }
1442 
1443     /**
1444      * Returns whether or not automatic drag handling is enabled.
1445      *
1446      * @return the value of the {@code dragEnabled} property
1447      * @see #setDragEnabled
1448      * @since 1.4
1449      */
1450     public boolean getDragEnabled() {
1451         return dragEnabled;
1452     }
1453 
1454     /**
1455      * Sets the drop mode for this component. For backward compatibility,
1456      * the default for this property is <code>DropMode.USE_SELECTION</code>.
1457      * Usage of one of the other modes is recommended, however, for an
1458      * improved user experience. <code>DropMode.ON</code>, for instance,
1459      * offers similar behavior of showing items as selected, but does so without
1460      * affecting the actual selection in the table.
1461      * <p>
1462      * <code>JTable</code> supports the following drop modes:
1463      * <ul>
1464      *    <li><code>DropMode.USE_SELECTION</code></li>
1465      *    <li><code>DropMode.ON</code></li>
1466      *    <li><code>DropMode.INSERT</code></li>
1467      *    <li><code>DropMode.INSERT_ROWS</code></li>
1468      *    <li><code>DropMode.INSERT_COLS</code></li>
1469      *    <li><code>DropMode.ON_OR_INSERT</code></li>
1470      *    <li><code>DropMode.ON_OR_INSERT_ROWS</code></li>
1471      *    <li><code>DropMode.ON_OR_INSERT_COLS</code></li>
1472      * </ul>
1473      * <p>
1474      * The drop mode is only meaningful if this component has a
1475      * <code>TransferHandler</code> that accepts drops.
1476      *
1477      * @param dropMode the drop mode to use
1478      * @throws IllegalArgumentException if the drop mode is unsupported
1479      *         or <code>null</code>
1480      * @see #getDropMode
1481      * @see #getDropLocation
1482      * @see #setTransferHandler
1483      * @see TransferHandler
1484      * @since 1.6
1485      */
1486     public final void setDropMode(DropMode dropMode) {
1487         if (dropMode != null) {
1488             switch (dropMode) {
1489                 case USE_SELECTION:
1490                 case ON:
1491                 case INSERT:
1492                 case INSERT_ROWS:
1493                 case INSERT_COLS:
1494                 case ON_OR_INSERT:
1495                 case ON_OR_INSERT_ROWS:
1496                 case ON_OR_INSERT_COLS:
1497                     this.dropMode = dropMode;
1498                     return;
1499             }
1500         }
1501 
1502         throw new IllegalArgumentException(dropMode + ": Unsupported drop mode for table");
1503     }
1504 
1505     /**
1506      * Returns the drop mode for this component.
1507      *
1508      * @return the drop mode for this component
1509      * @see #setDropMode
1510      * @since 1.6
1511      */
1512     public final DropMode getDropMode() {
1513         return dropMode;
1514     }
1515 
1516     /**
1517      * Calculates a drop location in this component, representing where a
1518      * drop at the given point should insert data.
1519      *
1520      * @param p the point to calculate a drop location for
1521      * @return the drop location, or <code>null</code>
1522      */
1523     DropLocation dropLocationForPoint(Point p) {
1524         DropLocation location = null;
1525 
1526         int row = rowAtPoint(p);
1527         int col = columnAtPoint(p);
1528         boolean outside = Boolean.TRUE == getClientProperty("Table.isFileList")
1529                           && SwingUtilities2.pointOutsidePrefSize(this, row, col, p);
1530 
1531         Rectangle rect = getCellRect(row, col, true);
1532         Section xSection, ySection;
1533         boolean between = false;
1534         boolean ltr = getComponentOrientation().isLeftToRight();
1535 
1536         switch(dropMode) {
1537             case USE_SELECTION:
1538             case ON:
1539                 if (row == -1 || col == -1 || outside) {
1540                     location = new DropLocation(p, -1, -1, false, false);
1541                 } else {
1542                     location = new DropLocation(p, row, col, false, false);
1543                 }
1544                 break;
1545             case INSERT:
1546                 if (row == -1 && col == -1) {
1547                     location = new DropLocation(p, 0, 0, true, true);
1548                     break;
1549                 }
1550 
1551                 xSection = SwingUtilities2.liesInHorizontal(rect, p, ltr, true);
1552 
1553                 if (row == -1) {
1554                     if (xSection == LEADING) {
1555                         location = new DropLocation(p, getRowCount(), col, true, true);
1556                     } else if (xSection == TRAILING) {
1557                         location = new DropLocation(p, getRowCount(), col + 1, true, true);
1558                     } else {
1559                         location = new DropLocation(p, getRowCount(), col, true, false);
1560                     }
1561                 } else if (xSection == LEADING || xSection == TRAILING) {
1562                     ySection = SwingUtilities2.liesInVertical(rect, p, true);
1563                     if (ySection == LEADING) {
1564                         between = true;
1565                     } else if (ySection == TRAILING) {
1566                         row++;
1567                         between = true;
1568                     }
1569 
1570                     location = new DropLocation(p, row,
1571                                                 xSection == TRAILING ? col + 1 : col,
1572                                                 between, true);
1573                 } else {
1574                     if (SwingUtilities2.liesInVertical(rect, p, false) == TRAILING) {
1575                         row++;
1576                     }
1577 
1578                     location = new DropLocation(p, row, col, true, false);
1579                 }
1580 
1581                 break;
1582             case INSERT_ROWS:
1583                 if (row == -1 && col == -1) {
1584                     location = new DropLocation(p, -1, -1, false, false);
1585                     break;
1586                 }
1587 
1588                 if (row == -1) {
1589                     location = new DropLocation(p, getRowCount(), col, true, false);
1590                     break;
1591                 }
1592 
1593                 if (SwingUtilities2.liesInVertical(rect, p, false) == TRAILING) {
1594                     row++;
1595                 }
1596 
1597                 location = new DropLocation(p, row, col, true, false);
1598                 break;
1599             case ON_OR_INSERT_ROWS:
1600                 if (row == -1 && col == -1) {
1601                     location = new DropLocation(p, -1, -1, false, false);
1602                     break;
1603                 }
1604 
1605                 if (row == -1) {
1606                     location = new DropLocation(p, getRowCount(), col, true, false);
1607                     break;
1608                 }
1609 
1610                 ySection = SwingUtilities2.liesInVertical(rect, p, true);
1611                 if (ySection == LEADING) {
1612                     between = true;
1613                 } else if (ySection == TRAILING) {
1614                     row++;
1615                     between = true;
1616                 }
1617 
1618                 location = new DropLocation(p, row, col, between, false);
1619                 break;
1620             case INSERT_COLS:
1621                 if (row == -1) {
1622                     location = new DropLocation(p, -1, -1, false, false);
1623                     break;
1624                 }
1625 
1626                 if (col == -1) {
1627                     location = new DropLocation(p, getColumnCount(), col, false, true);
1628                     break;
1629                 }
1630 
1631                 if (SwingUtilities2.liesInHorizontal(rect, p, ltr, false) == TRAILING) {
1632                     col++;
1633                 }
1634 
1635                 location = new DropLocation(p, row, col, false, true);
1636                 break;
1637             case ON_OR_INSERT_COLS:
1638                 if (row == -1) {
1639                     location = new DropLocation(p, -1, -1, false, false);
1640                     break;
1641                 }
1642 
1643                 if (col == -1) {
1644                     location = new DropLocation(p, row, getColumnCount(), false, true);
1645                     break;
1646                 }
1647 
1648                 xSection = SwingUtilities2.liesInHorizontal(rect, p, ltr, true);
1649                 if (xSection == LEADING) {
1650                     between = true;
1651                 } else if (xSection == TRAILING) {
1652                     col++;
1653                     between = true;
1654                 }
1655 
1656                 location = new DropLocation(p, row, col, false, between);
1657                 break;
1658             case ON_OR_INSERT:
1659                 if (row == -1 && col == -1) {
1660                     location = new DropLocation(p, 0, 0, true, true);
1661                     break;
1662                 }
1663 
1664                 xSection = SwingUtilities2.liesInHorizontal(rect, p, ltr, true);
1665 
1666                 if (row == -1) {
1667                     if (xSection == LEADING) {
1668                         location = new DropLocation(p, getRowCount(), col, true, true);
1669                     } else if (xSection == TRAILING) {
1670                         location = new DropLocation(p, getRowCount(), col + 1, true, true);
1671                     } else {
1672                         location = new DropLocation(p, getRowCount(), col, true, false);
1673                     }
1674 
1675                     break;
1676                 }
1677 
1678                 ySection = SwingUtilities2.liesInVertical(rect, p, true);
1679                 if (ySection == LEADING) {
1680                     between = true;
1681                 } else if (ySection == TRAILING) {
1682                     row++;
1683                     between = true;
1684                 }
1685 
1686                 location = new DropLocation(p, row,
1687                                             xSection == TRAILING ? col + 1 : col,
1688                                             between,
1689                                             xSection != MIDDLE);
1690 
1691                 break;
1692             default:
1693                 assert false : "Unexpected drop mode";
1694         }
1695 
1696         return location;
1697     }
1698 
1699     /**
1700      * Called to set or clear the drop location during a DnD operation.
1701      * In some cases, the component may need to use it's internal selection
1702      * temporarily to indicate the drop location. To help facilitate this,
1703      * this method returns and accepts as a parameter a state object.
1704      * This state object can be used to store, and later restore, the selection
1705      * state. Whatever this method returns will be passed back to it in
1706      * future calls, as the state parameter. If it wants the DnD system to
1707      * continue storing the same state, it must pass it back every time.
1708      * Here's how this is used:
1709      * <p>
1710      * Let's say that on the first call to this method the component decides
1711      * to save some state (because it is about to use the selection to show
1712      * a drop index). It can return a state object to the caller encapsulating
1713      * any saved selection state. On a second call, let's say the drop location
1714      * is being changed to something else. The component doesn't need to
1715      * restore anything yet, so it simply passes back the same state object
1716      * to have the DnD system continue storing it. Finally, let's say this
1717      * method is messaged with <code>null</code>. This means DnD
1718      * is finished with this component for now, meaning it should restore
1719      * state. At this point, it can use the state parameter to restore
1720      * said state, and of course return <code>null</code> since there's
1721      * no longer anything to store.
1722      *
1723      * @param location the drop location (as calculated by
1724      *        <code>dropLocationForPoint</code>) or <code>null</code>
1725      *        if there's no longer a valid drop location
1726      * @param state the state object saved earlier for this component,
1727      *        or <code>null</code>
1728      * @param forDrop whether or not the method is being called because an
1729      *        actual drop occurred
1730      * @return any saved state for this component, or <code>null</code> if none
1731      */
1732     Object setDropLocation(TransferHandler.DropLocation location,
1733                            Object state,
1734                            boolean forDrop) {
1735 
1736         Object retVal = null;
1737         DropLocation tableLocation = (DropLocation)location;
1738 
1739         if (dropMode == DropMode.USE_SELECTION) {
1740             if (tableLocation == null) {
1741                 if (!forDrop && state != null) {
1742                     clearSelection();
1743 
1744                     int[] rows = ((int[][])state)[0];
1745                     int[] cols = ((int[][])state)[1];
1746                     int[] anchleads = ((int[][])state)[2];
1747 
1748                     for (int row : rows) {
1749                         addRowSelectionInterval(row, row);
1750                     }
1751 
1752                     for (int col : cols) {
1753                         addColumnSelectionInterval(col, col);
1754                     }
1755 
1756                     SwingUtilities2.setLeadAnchorWithoutSelection(
1757                             getSelectionModel(), anchleads[1], anchleads[0]);
1758 
1759                     SwingUtilities2.setLeadAnchorWithoutSelection(
1760                             getColumnModel().getSelectionModel(),
1761                             anchleads[3], anchleads[2]);
1762                 }
1763             } else {
1764                 if (dropLocation == null) {
1765                     retVal = new int[][]{
1766                         getSelectedRows(),
1767                         getSelectedColumns(),
1768                         {getAdjustedIndex(getSelectionModel()
1769                              .getAnchorSelectionIndex(), true),
1770                          getAdjustedIndex(getSelectionModel()
1771                              .getLeadSelectionIndex(), true),
1772                          getAdjustedIndex(getColumnModel().getSelectionModel()
1773                              .getAnchorSelectionIndex(), false),
1774                          getAdjustedIndex(getColumnModel().getSelectionModel()
1775                              .getLeadSelectionIndex(), false)}};
1776                 } else {
1777                     retVal = state;
1778                 }
1779 
1780                 if (tableLocation.getRow() == -1) {
1781                     clearSelectionAndLeadAnchor();
1782                 } else {
1783                     setRowSelectionInterval(tableLocation.getRow(),
1784                                             tableLocation.getRow());
1785                     setColumnSelectionInterval(tableLocation.getColumn(),
1786                                                tableLocation.getColumn());
1787                 }
1788             }
1789         }
1790 
1791         DropLocation old = dropLocation;
1792         dropLocation = tableLocation;
1793         firePropertyChange("dropLocation", old, dropLocation);
1794 
1795         return retVal;
1796     }
1797 
1798     /**
1799      * Returns the location that this component should visually indicate
1800      * as the drop location during a DnD operation over the component,
1801      * or {@code null} if no location is to currently be shown.
1802      * <p>
1803      * This method is not meant for querying the drop location
1804      * from a {@code TransferHandler}, as the drop location is only
1805      * set after the {@code TransferHandler}'s <code>canImport</code>
1806      * has returned and has allowed for the location to be shown.
1807      * <p>
1808      * When this property changes, a property change event with
1809      * name "dropLocation" is fired by the component.
1810      *
1811      * @return the drop location
1812      * @see #setDropMode
1813      * @see TransferHandler#canImport(TransferHandler.TransferSupport)
1814      * @since 1.6
1815      */
1816     public final DropLocation getDropLocation() {
1817         return dropLocation;
1818     }
1819 
1820     /**
1821      * Specifies whether a {@code RowSorter} should be created for the
1822      * table whenever its model changes.
1823      * <p>
1824      * When {@code setAutoCreateRowSorter(true)} is invoked, a {@code
1825      * TableRowSorter} is immediately created and installed on the
1826      * table.  While the {@code autoCreateRowSorter} property remains
1827      * {@code true}, every time the model is changed, a new {@code
1828      * TableRowSorter} is created and set as the table's row sorter.
1829      * The default value for the {@code autoCreateRowSorter}
1830      * property is {@code false}.
1831      *
1832      * @param autoCreateRowSorter whether or not a {@code RowSorter}
1833      *        should be automatically created
1834      * @see javax.swing.table.TableRowSorter
1835      * @beaninfo
1836      *        bound: true
1837      *    preferred: true
1838      *  description: Whether or not to turn on sorting by default.
1839      * @since 1.6
1840      */
1841     public void setAutoCreateRowSorter(boolean autoCreateRowSorter) {
1842         boolean oldValue = this.autoCreateRowSorter;
1843         this.autoCreateRowSorter = autoCreateRowSorter;
1844         if (autoCreateRowSorter) {
1845             setRowSorter(new TableRowSorter<TableModel>(getModel()));
1846         }
1847         firePropertyChange("autoCreateRowSorter", oldValue,
1848                            autoCreateRowSorter);
1849     }
1850 
1851     /**
1852      * Returns {@code true} if whenever the model changes, a new
1853      * {@code RowSorter} should be created and installed
1854      * as the table's sorter; otherwise, returns {@code false}.
1855      *
1856      * @return true if a {@code RowSorter} should be created when
1857      *         the model changes
1858      * @since 1.6
1859      */
1860     public boolean getAutoCreateRowSorter() {
1861         return autoCreateRowSorter;
1862     }
1863 
1864     /**
1865      * Specifies whether the selection should be updated after sorting.
1866      * If true, on sorting the selection is reset such that
1867      * the same rows, in terms of the model, remain selected.  The default
1868      * is true.
1869      *
1870      * @param update whether or not to update the selection on sorting
1871      * @beaninfo
1872      *        bound: true
1873      *       expert: true
1874      *  description: Whether or not to update the selection on sorting
1875      * @since 1.6
1876      */
1877     public void setUpdateSelectionOnSort(boolean update) {
1878         if (updateSelectionOnSort != update) {
1879             updateSelectionOnSort = update;
1880             firePropertyChange("updateSelectionOnSort", !update, update);
1881         }
1882     }
1883 
1884     /**
1885      * Returns true if the selection should be updated after sorting.
1886      *
1887      * @return whether to update the selection on a sort
1888      * @since 1.6
1889      */
1890     public boolean getUpdateSelectionOnSort() {
1891         return updateSelectionOnSort;
1892     }
1893 
1894     /**
1895      * Sets the <code>RowSorter</code>.  <code>RowSorter</code> is used
1896      * to provide sorting and filtering to a <code>JTable</code>.
1897      * <p>
1898      * This method clears the selection and resets any variable row heights.
1899      * <p>
1900      * This method fires a <code>PropertyChangeEvent</code> when appropriate,
1901      * with the property name <code>"rowSorter"</code>.  For
1902      * backward-compatibility, this method fires an additional event with the
1903      * property name <code>"sorter"</code>.
1904      * <p>
1905      * If the underlying model of the <code>RowSorter</code> differs from
1906      * that of this <code>JTable</code> undefined behavior will result.
1907      *
1908      * @param sorter the <code>RowSorter</code>; <code>null</code> turns
1909      *        sorting off
1910      * @see javax.swing.table.TableRowSorter
1911      * @beaninfo
1912      *        bound: true
1913      *  description: The table's RowSorter
1914      * @since 1.6
1915      */
1916     public void setRowSorter(RowSorter<? extends TableModel> sorter) {
1917         RowSorter<? extends TableModel> oldRowSorter = null;
1918         if (sortManager != null) {
1919             oldRowSorter = sortManager.sorter;
1920             sortManager.dispose();
1921             sortManager = null;
1922         }
1923         rowModel = null;
1924         clearSelectionAndLeadAnchor();
1925         if (sorter != null) {
1926             sortManager = new SortManager(sorter);
1927         }
1928         resizeAndRepaint();
1929         firePropertyChange("rowSorter", oldRowSorter, sorter);
1930         firePropertyChange("sorter", oldRowSorter, sorter);
1931     }
1932 
1933     /**
1934      * Returns the object responsible for sorting.
1935      *
1936      * @return the object responsible for sorting
1937      * @since 1.6
1938      */
1939     public RowSorter<? extends TableModel> getRowSorter() {
1940         return (sortManager != null) ? sortManager.sorter : null;
1941     }
1942 
1943 //
1944 // Selection methods
1945 //
1946     /**
1947      * Sets the table's selection mode to allow only single selections, a single
1948      * contiguous interval, or multiple intervals.
1949      * <P>
1950      * <b>Note:</b>
1951      * <code>JTable</code> provides all the methods for handling
1952      * column and row selection.  When setting states,
1953      * such as <code>setSelectionMode</code>, it not only
1954      * updates the mode for the row selection model but also sets similar
1955      * values in the selection model of the <code>columnModel</code>.
1956      * If you want to have the row and column selection models operating
1957      * in different modes, set them both directly.
1958      * <p>
1959      * Both the row and column selection models for <code>JTable</code>
1960      * default to using a <code>DefaultListSelectionModel</code>
1961      * so that <code>JTable</code> works the same way as the
1962      * <code>JList</code>. See the <code>setSelectionMode</code> method
1963      * in <code>JList</code> for details about the modes.
1964      *
1965      * @see JList#setSelectionMode
1966      * @beaninfo
1967      * description: The selection mode used by the row and column selection models.
1968      *        enum: SINGLE_SELECTION            ListSelectionModel.SINGLE_SELECTION
1969      *              SINGLE_INTERVAL_SELECTION   ListSelectionModel.SINGLE_INTERVAL_SELECTION
1970      *              MULTIPLE_INTERVAL_SELECTION ListSelectionModel.MULTIPLE_INTERVAL_SELECTION
1971      */
1972     public void setSelectionMode(int selectionMode) {
1973         clearSelection();
1974         getSelectionModel().setSelectionMode(selectionMode);
1975         getColumnModel().getSelectionModel().setSelectionMode(selectionMode);
1976     }
1977 
1978     /**
1979      * Sets whether the rows in this model can be selected.
1980      *
1981      * @param rowSelectionAllowed   true if this model will allow row selection
1982      * @see #getRowSelectionAllowed
1983      * @beaninfo
1984      *  bound: true
1985      *    attribute: visualUpdate true
1986      *  description: If true, an entire row is selected for each selected cell.
1987      */
1988     public void setRowSelectionAllowed(boolean rowSelectionAllowed) {
1989         boolean old = this.rowSelectionAllowed;
1990         this.rowSelectionAllowed = rowSelectionAllowed;
1991         if (old != rowSelectionAllowed) {
1992             repaint();
1993         }
1994         firePropertyChange("rowSelectionAllowed", old, rowSelectionAllowed);
1995     }
1996 
1997     /**
1998      * Returns true if rows can be selected.
1999      *
2000      * @return true if rows can be selected, otherwise false
2001      * @see #setRowSelectionAllowed
2002      */
2003     public boolean getRowSelectionAllowed() {
2004         return rowSelectionAllowed;
2005     }
2006 
2007     /**
2008      * Sets whether the columns in this model can be selected.
2009      *
2010      * @param columnSelectionAllowed   true if this model will allow column selection
2011      * @see #getColumnSelectionAllowed
2012      * @beaninfo
2013      *  bound: true
2014      *    attribute: visualUpdate true
2015      *  description: If true, an entire column is selected for each selected cell.
2016      */
2017     public void setColumnSelectionAllowed(boolean columnSelectionAllowed) {
2018         boolean old = columnModel.getColumnSelectionAllowed();
2019         columnModel.setColumnSelectionAllowed(columnSelectionAllowed);
2020         if (old != columnSelectionAllowed) {
2021             repaint();
2022         }
2023         firePropertyChange("columnSelectionAllowed", old, columnSelectionAllowed);
2024     }
2025 
2026     /**
2027      * Returns true if columns can be selected.
2028      *
2029      * @return true if columns can be selected, otherwise false
2030      * @see #setColumnSelectionAllowed
2031      */
2032     public boolean getColumnSelectionAllowed() {
2033         return columnModel.getColumnSelectionAllowed();
2034     }
2035 
2036     /**
2037      * Sets whether this table allows both a column selection and a
2038      * row selection to exist simultaneously. When set,
2039      * the table treats the intersection of the row and column selection
2040      * models as the selected cells. Override <code>isCellSelected</code> to
2041      * change this default behavior. This method is equivalent to setting
2042      * both the <code>rowSelectionAllowed</code> property and
2043      * <code>columnSelectionAllowed</code> property of the
2044      * <code>columnModel</code> to the supplied value.
2045      *
2046      * @param  cellSelectionEnabled     true if simultaneous row and column
2047      *                                  selection is allowed
2048      * @see #getCellSelectionEnabled
2049      * @see #isCellSelected
2050      * @beaninfo
2051      *  bound: true
2052      *    attribute: visualUpdate true
2053      *  description: Select a rectangular region of cells rather than
2054      *               rows or columns.
2055      */
2056     public void setCellSelectionEnabled(boolean cellSelectionEnabled) {
2057         setRowSelectionAllowed(cellSelectionEnabled);
2058         setColumnSelectionAllowed(cellSelectionEnabled);
2059         boolean old = this.cellSelectionEnabled;
2060         this.cellSelectionEnabled = cellSelectionEnabled;
2061         firePropertyChange("cellSelectionEnabled", old, cellSelectionEnabled);
2062     }
2063 
2064     /**
2065      * Returns true if both row and column selection models are enabled.
2066      * Equivalent to <code>getRowSelectionAllowed() &amp;&amp;
2067      * getColumnSelectionAllowed()</code>.
2068      *
2069      * @return true if both row and column selection models are enabled
2070      *
2071      * @see #setCellSelectionEnabled
2072      */
2073     public boolean getCellSelectionEnabled() {
2074         return getRowSelectionAllowed() && getColumnSelectionAllowed();
2075     }
2076 
2077     /**
2078      *  Selects all rows, columns, and cells in the table.
2079      */
2080     public void selectAll() {
2081         // If I'm currently editing, then I should stop editing
2082         if (isEditing()) {
2083             removeEditor();
2084         }
2085         if (getRowCount() > 0 && getColumnCount() > 0) {
2086             int oldLead;
2087             int oldAnchor;
2088             ListSelectionModel selModel;
2089 
2090             selModel = selectionModel;
2091             selModel.setValueIsAdjusting(true);
2092             oldLead = getAdjustedIndex(selModel.getLeadSelectionIndex(), true);
2093             oldAnchor = getAdjustedIndex(selModel.getAnchorSelectionIndex(), true);
2094 
2095             setRowSelectionInterval(0, getRowCount()-1);
2096 
2097             // this is done to restore the anchor and lead
2098             SwingUtilities2.setLeadAnchorWithoutSelection(selModel, oldLead, oldAnchor);
2099 
2100             selModel.setValueIsAdjusting(false);
2101 
2102             selModel = columnModel.getSelectionModel();
2103             selModel.setValueIsAdjusting(true);
2104             oldLead = getAdjustedIndex(selModel.getLeadSelectionIndex(), false);
2105             oldAnchor = getAdjustedIndex(selModel.getAnchorSelectionIndex(), false);
2106 
2107             setColumnSelectionInterval(0, getColumnCount()-1);
2108 
2109             // this is done to restore the anchor and lead
2110             SwingUtilities2.setLeadAnchorWithoutSelection(selModel, oldLead, oldAnchor);
2111 
2112             selModel.setValueIsAdjusting(false);
2113         }
2114     }
2115 
2116     /**
2117      * Deselects all selected columns and rows.
2118      */
2119     public void clearSelection() {
2120         selectionModel.clearSelection();
2121         columnModel.getSelectionModel().clearSelection();
2122     }
2123 
2124     private void clearSelectionAndLeadAnchor() {
2125         selectionModel.setValueIsAdjusting(true);
2126         columnModel.getSelectionModel().setValueIsAdjusting(true);
2127 
2128         clearSelection();
2129 
2130         selectionModel.setAnchorSelectionIndex(-1);
2131         selectionModel.setLeadSelectionIndex(-1);
2132         columnModel.getSelectionModel().setAnchorSelectionIndex(-1);
2133         columnModel.getSelectionModel().setLeadSelectionIndex(-1);
2134 
2135         selectionModel.setValueIsAdjusting(false);
2136         columnModel.getSelectionModel().setValueIsAdjusting(false);
2137     }
2138 
2139     private int getAdjustedIndex(int index, boolean row) {
2140         int compare = row ? getRowCount() : getColumnCount();
2141         return index < compare ? index : -1;
2142     }
2143 
2144     private int boundRow(int row) throws IllegalArgumentException {
2145         if (row < 0 || row >= getRowCount()) {
2146             throw new IllegalArgumentException("Row index out of range");
2147         }
2148         return row;
2149     }
2150 
2151     private int boundColumn(int col) {
2152         if (col< 0 || col >= getColumnCount()) {
2153             throw new IllegalArgumentException("Column index out of range");
2154         }
2155         return col;
2156     }
2157 
2158     /**
2159      * Selects the rows from <code>index0</code> to <code>index1</code>,
2160      * inclusive.
2161      *
2162      * @exception IllegalArgumentException      if <code>index0</code> or
2163      *                                          <code>index1</code> lie outside
2164      *                                          [0, <code>getRowCount()</code>-1]
2165      * @param   index0 one end of the interval
2166      * @param   index1 the other end of the interval
2167      */
2168     public void setRowSelectionInterval(int index0, int index1) {
2169         selectionModel.setSelectionInterval(boundRow(index0), boundRow(index1));
2170     }
2171 
2172     /**
2173      * Selects the columns from <code>index0</code> to <code>index1</code>,
2174      * inclusive.
2175      *
2176      * @exception IllegalArgumentException      if <code>index0</code> or
2177      *                                          <code>index1</code> lie outside
2178      *                                          [0, <code>getColumnCount()</code>-1]
2179      * @param   index0 one end of the interval
2180      * @param   index1 the other end of the interval
2181      */
2182     public void setColumnSelectionInterval(int index0, int index1) {
2183         columnModel.getSelectionModel().setSelectionInterval(boundColumn(index0), boundColumn(index1));
2184     }
2185 
2186     /**
2187      * Adds the rows from <code>index0</code> to <code>index1</code>, inclusive, to
2188      * the current selection.
2189      *
2190      * @exception IllegalArgumentException      if <code>index0</code> or <code>index1</code>
2191      *                                          lie outside [0, <code>getRowCount()</code>-1]
2192      * @param   index0 one end of the interval
2193      * @param   index1 the other end of the interval
2194      */
2195     public void addRowSelectionInterval(int index0, int index1) {
2196         selectionModel.addSelectionInterval(boundRow(index0), boundRow(index1));
2197     }
2198 
2199     /**
2200      * Adds the columns from <code>index0</code> to <code>index1</code>,
2201      * inclusive, to the current selection.
2202      *
2203      * @exception IllegalArgumentException      if <code>index0</code> or
2204      *                                          <code>index1</code> lie outside
2205      *                                          [0, <code>getColumnCount()</code>-1]
2206      * @param   index0 one end of the interval
2207      * @param   index1 the other end of the interval
2208      */
2209     public void addColumnSelectionInterval(int index0, int index1) {
2210         columnModel.getSelectionModel().addSelectionInterval(boundColumn(index0), boundColumn(index1));
2211     }
2212 
2213     /**
2214      * Deselects the rows from <code>index0</code> to <code>index1</code>, inclusive.
2215      *
2216      * @exception IllegalArgumentException      if <code>index0</code> or
2217      *                                          <code>index1</code> lie outside
2218      *                                          [0, <code>getRowCount()</code>-1]
2219      * @param   index0 one end of the interval
2220      * @param   index1 the other end of the interval
2221      */
2222     public void removeRowSelectionInterval(int index0, int index1) {
2223         selectionModel.removeSelectionInterval(boundRow(index0), boundRow(index1));
2224     }
2225 
2226     /**
2227      * Deselects the columns from <code>index0</code> to <code>index1</code>, inclusive.
2228      *
2229      * @exception IllegalArgumentException      if <code>index0</code> or
2230      *                                          <code>index1</code> lie outside
2231      *                                          [0, <code>getColumnCount()</code>-1]
2232      * @param   index0 one end of the interval
2233      * @param   index1 the other end of the interval
2234      */
2235     public void removeColumnSelectionInterval(int index0, int index1) {
2236         columnModel.getSelectionModel().removeSelectionInterval(boundColumn(index0), boundColumn(index1));
2237     }
2238 
2239     /**
2240      * Returns the index of the first selected row, -1 if no row is selected.
2241      * @return the index of the first selected row
2242      */
2243     public int getSelectedRow() {
2244         return selectionModel.getMinSelectionIndex();
2245     }
2246 
2247     /**
2248      * Returns the index of the first selected column,
2249      * -1 if no column is selected.
2250      * @return the index of the first selected column
2251      */
2252     public int getSelectedColumn() {
2253         return columnModel.getSelectionModel().getMinSelectionIndex();
2254     }
2255 
2256     /**
2257      * Returns the indices of all selected rows.
2258      *
2259      * @return an array of integers containing the indices of all selected rows,
2260      *         or an empty array if no row is selected
2261      * @see #getSelectedRow
2262      */
2263     public int[] getSelectedRows() {
2264         int iMin = selectionModel.getMinSelectionIndex();
2265         int iMax = selectionModel.getMaxSelectionIndex();
2266 
2267         if ((iMin == -1) || (iMax == -1)) {
2268             return new int[0];
2269         }
2270 
2271         int[] rvTmp = new int[1+ (iMax - iMin)];
2272         int n = 0;
2273         for(int i = iMin; i <= iMax; i++) {
2274             if (selectionModel.isSelectedIndex(i)) {
2275                 rvTmp[n++] = i;
2276             }
2277         }
2278         int[] rv = new int[n];
2279         System.arraycopy(rvTmp, 0, rv, 0, n);
2280         return rv;
2281     }
2282 
2283     /**
2284      * Returns the indices of all selected columns.
2285      *
2286      * @return an array of integers containing the indices of all selected columns,
2287      *         or an empty array if no column is selected
2288      * @see #getSelectedColumn
2289      */
2290     public int[] getSelectedColumns() {
2291         return columnModel.getSelectedColumns();
2292     }
2293 
2294     /**
2295      * Returns the number of selected rows.
2296      *
2297      * @return the number of selected rows, 0 if no rows are selected
2298      */
2299     public int getSelectedRowCount() {
2300         int iMin = selectionModel.getMinSelectionIndex();
2301         int iMax = selectionModel.getMaxSelectionIndex();
2302         int count = 0;
2303 
2304         for(int i = iMin; i <= iMax; i++) {
2305             if (selectionModel.isSelectedIndex(i)) {
2306                 count++;
2307             }
2308         }
2309         return count;
2310     }
2311 
2312     /**
2313      * Returns the number of selected columns.
2314      *
2315      * @return the number of selected columns, 0 if no columns are selected
2316      */
2317     public int getSelectedColumnCount() {
2318         return columnModel.getSelectedColumnCount();
2319     }
2320 
2321     /**
2322      * Returns true if the specified index is in the valid range of rows,
2323      * and the row at that index is selected.
2324      *
2325      * @return true if <code>row</code> is a valid index and the row at
2326      *              that index is selected (where 0 is the first row)
2327      */
2328     public boolean isRowSelected(int row) {
2329         return selectionModel.isSelectedIndex(row);
2330     }
2331 
2332     /**
2333      * Returns true if the specified index is in the valid range of columns,
2334      * and the column at that index is selected.
2335      *
2336      * @param   column   the column in the column model
2337      * @return true if <code>column</code> is a valid index and the column at
2338      *              that index is selected (where 0 is the first column)
2339      */
2340     public boolean isColumnSelected(int column) {
2341         return columnModel.getSelectionModel().isSelectedIndex(column);
2342     }
2343 
2344     /**
2345      * Returns true if the specified indices are in the valid range of rows
2346      * and columns and the cell at the specified position is selected.
2347      * @param row   the row being queried
2348      * @param column  the column being queried
2349      *
2350      * @return true if <code>row</code> and <code>column</code> are valid indices
2351      *              and the cell at index <code>(row, column)</code> is selected,
2352      *              where the first row and first column are at index 0
2353      */
2354     public boolean isCellSelected(int row, int column) {
2355         if (!getRowSelectionAllowed() && !getColumnSelectionAllowed()) {
2356             return false;
2357         }
2358         return (!getRowSelectionAllowed() || isRowSelected(row)) &&
2359                (!getColumnSelectionAllowed() || isColumnSelected(column));
2360     }
2361 
2362     private void changeSelectionModel(ListSelectionModel sm, int index,
2363                                       boolean toggle, boolean extend, boolean selected,
2364                                       int anchor, boolean anchorSelected) {
2365         if (extend) {
2366             if (toggle) {
2367                 if (anchorSelected) {
2368                     sm.addSelectionInterval(anchor, index);
2369                 } else {
2370                     sm.removeSelectionInterval(anchor, index);
2371                     // this is a Windows-only behavior that we want for file lists
2372                     if (Boolean.TRUE == getClientProperty("Table.isFileList")) {
2373                         sm.addSelectionInterval(index, index);
2374                         sm.setAnchorSelectionIndex(anchor);
2375                     }
2376                 }
2377             }
2378             else {
2379                 sm.setSelectionInterval(anchor, index);
2380             }
2381         }
2382         else {
2383             if (toggle) {
2384                 if (selected) {
2385                     sm.removeSelectionInterval(index, index);
2386                 }
2387                 else {
2388                     sm.addSelectionInterval(index, index);
2389                 }
2390             }
2391             else {
2392                 sm.setSelectionInterval(index, index);
2393             }
2394         }
2395     }
2396 
2397     /**
2398      * Updates the selection models of the table, depending on the state of the
2399      * two flags: <code>toggle</code> and <code>extend</code>. Most changes
2400      * to the selection that are the result of keyboard or mouse events received
2401      * by the UI are channeled through this method so that the behavior may be
2402      * overridden by a subclass. Some UIs may need more functionality than
2403      * this method provides, such as when manipulating the lead for discontiguous
2404      * selection, and may not call into this method for some selection changes.
2405      * <p>
2406      * This implementation uses the following conventions:
2407      * <ul>
2408      * <li> <code>toggle</code>: <em>false</em>, <code>extend</code>: <em>false</em>.
2409      *      Clear the previous selection and ensure the new cell is selected.
2410      * <li> <code>toggle</code>: <em>false</em>, <code>extend</code>: <em>true</em>.
2411      *      Extend the previous selection from the anchor to the specified cell,
2412      *      clearing all other selections.
2413      * <li> <code>toggle</code>: <em>true</em>, <code>extend</code>: <em>false</em>.
2414      *      If the specified cell is selected, deselect it. If it is not selected, select it.
2415      * <li> <code>toggle</code>: <em>true</em>, <code>extend</code>: <em>true</em>.
2416      *      Apply the selection state of the anchor to all cells between it and the
2417      *      specified cell.
2418      * </ul>
2419      * @param  rowIndex   affects the selection at <code>row</code>
2420      * @param  columnIndex  affects the selection at <code>column</code>
2421      * @param  toggle  see description above
2422      * @param  extend  if true, extend the current selection
2423      *
2424      * @since 1.3
2425      */
2426     public void changeSelection(int rowIndex, int columnIndex, boolean toggle, boolean extend) {
2427         ListSelectionModel rsm = getSelectionModel();
2428         ListSelectionModel csm = getColumnModel().getSelectionModel();
2429 
2430         int anchorRow = getAdjustedIndex(rsm.getAnchorSelectionIndex(), true);
2431         int anchorCol = getAdjustedIndex(csm.getAnchorSelectionIndex(), false);
2432 
2433         boolean anchorSelected = true;
2434 
2435         if (anchorRow == -1) {
2436             if (getRowCount() > 0) {
2437                 anchorRow = 0;
2438             }
2439             anchorSelected = false;
2440         }
2441 
2442         if (anchorCol == -1) {
2443             if (getColumnCount() > 0) {
2444                 anchorCol = 0;
2445             }
2446             anchorSelected = false;
2447         }
2448 
2449         // Check the selection here rather than in each selection model.
2450         // This is significant in cell selection mode if we are supposed
2451         // to be toggling the selection. In this case it is better to
2452         // ensure that the cell's selection state will indeed be changed.
2453         // If this were done in the code for the selection model it
2454         // might leave a cell in selection state if the row was
2455         // selected but the column was not - as it would toggle them both.
2456         boolean selected = isCellSelected(rowIndex, columnIndex);
2457         anchorSelected = anchorSelected && isCellSelected(anchorRow, anchorCol);
2458 
2459         changeSelectionModel(csm, columnIndex, toggle, extend, selected,
2460                              anchorCol, anchorSelected);
2461         changeSelectionModel(rsm, rowIndex, toggle, extend, selected,
2462                              anchorRow, anchorSelected);
2463 
2464         // Scroll after changing the selection as blit scrolling is immediate,
2465         // so that if we cause the repaint after the scroll we end up painting
2466         // everything!
2467         if (getAutoscrolls()) {
2468             Rectangle cellRect = getCellRect(rowIndex, columnIndex, false);
2469             if (cellRect != null) {
2470                 scrollRectToVisible(cellRect);
2471             }
2472         }
2473     }
2474 
2475     /**
2476      * Returns the foreground color for selected cells.
2477      *
2478      * @return the <code>Color</code> object for the foreground property
2479      * @see #setSelectionForeground
2480      * @see #setSelectionBackground
2481      */
2482     public Color getSelectionForeground() {
2483         return selectionForeground;
2484     }
2485 
2486     /**
2487      * Sets the foreground color for selected cells.  Cell renderers
2488      * can use this color to render text and graphics for selected
2489      * cells.
2490      * <p>
2491      * The default value of this property is defined by the look
2492      * and feel implementation.
2493      * <p>
2494      * This is a <a href="https://docs.oracle.com/javase/tutorial/javabeans/writing/properties.html">JavaBeans</a> bound property.
2495      *
2496      * @param selectionForeground  the <code>Color</code> to use in the foreground
2497      *                             for selected list items
2498      * @see #getSelectionForeground
2499      * @see #setSelectionBackground
2500      * @see #setForeground
2501      * @see #setBackground
2502      * @see #setFont
2503      * @beaninfo
2504      *       bound: true
2505      * description: A default foreground color for selected cells.
2506      */
2507     public void setSelectionForeground(Color selectionForeground) {
2508         Color old = this.selectionForeground;
2509         this.selectionForeground = selectionForeground;
2510         firePropertyChange("selectionForeground", old, selectionForeground);
2511         repaint();
2512     }
2513 
2514     /**
2515      * Returns the background color for selected cells.
2516      *
2517      * @return the <code>Color</code> used for the background of selected list items
2518      * @see #setSelectionBackground
2519      * @see #setSelectionForeground
2520      */
2521     public Color getSelectionBackground() {
2522         return selectionBackground;
2523     }
2524 
2525     /**
2526      * Sets the background color for selected cells.  Cell renderers
2527      * can use this color to the fill selected cells.
2528      * <p>
2529      * The default value of this property is defined by the look
2530      * and feel implementation.
2531      * <p>
2532      * This is a <a href="https://docs.oracle.com/javase/tutorial/javabeans/writing/properties.html">JavaBeans</a> bound property.
2533      *
2534      * @param selectionBackground  the <code>Color</code> to use for the background
2535      *                             of selected cells
2536      * @see #getSelectionBackground
2537      * @see #setSelectionForeground
2538      * @see #setForeground
2539      * @see #setBackground
2540      * @see #setFont
2541      * @beaninfo
2542      *       bound: true
2543      * description: A default background color for selected cells.
2544      */
2545     public void setSelectionBackground(Color selectionBackground) {
2546         Color old = this.selectionBackground;
2547         this.selectionBackground = selectionBackground;
2548         firePropertyChange("selectionBackground", old, selectionBackground);
2549         repaint();
2550     }
2551 
2552     /**
2553      * Returns the <code>TableColumn</code> object for the column in the table
2554      * whose identifier is equal to <code>identifier</code>, when compared using
2555      * <code>equals</code>.
2556      *
2557      * @return  the <code>TableColumn</code> object that matches the identifier
2558      * @exception IllegalArgumentException      if <code>identifier</code> is <code>null</code> or no <code>TableColumn</code> has this identifier
2559      *
2560      * @param   identifier                      the identifier object
2561      */
2562     public TableColumn getColumn(Object identifier) {
2563         TableColumnModel cm = getColumnModel();
2564         int columnIndex = cm.getColumnIndex(identifier);
2565         return cm.getColumn(columnIndex);
2566     }
2567 
2568 //
2569 // Informally implement the TableModel interface.
2570 //
2571 
2572     /**
2573      * Maps the index of the column in the view at
2574      * <code>viewColumnIndex</code> to the index of the column
2575      * in the table model.  Returns the index of the corresponding
2576      * column in the model.  If <code>viewColumnIndex</code>
2577      * is less than zero, returns <code>viewColumnIndex</code>.
2578      *
2579      * @param   viewColumnIndex     the index of the column in the view
2580      * @return  the index of the corresponding column in the model
2581      *
2582      * @see #convertColumnIndexToView
2583      */
2584     public int convertColumnIndexToModel(int viewColumnIndex) {
2585         return SwingUtilities2.convertColumnIndexToModel(
2586                 getColumnModel(), viewColumnIndex);
2587     }
2588 
2589     /**
2590      * Maps the index of the column in the table model at
2591      * <code>modelColumnIndex</code> to the index of the column
2592      * in the view.  Returns the index of the
2593      * corresponding column in the view; returns -1 if this column is not
2594      * being displayed.  If <code>modelColumnIndex</code> is less than zero,
2595      * returns <code>modelColumnIndex</code>.
2596      *
2597      * @param   modelColumnIndex     the index of the column in the model
2598      * @return   the index of the corresponding column in the view
2599      *
2600      * @see #convertColumnIndexToModel
2601      */
2602     public int convertColumnIndexToView(int modelColumnIndex) {
2603         return SwingUtilities2.convertColumnIndexToView(
2604                 getColumnModel(), modelColumnIndex);
2605     }
2606 
2607     /**
2608      * Maps the index of the row in terms of the
2609      * <code>TableModel</code> to the view.  If the contents of the
2610      * model are not sorted the model and view indices are the same.
2611      *
2612      * @param modelRowIndex the index of the row in terms of the model
2613      * @return the index of the corresponding row in the view, or -1 if
2614      *         the row isn't visible
2615      * @throws IndexOutOfBoundsException if sorting is enabled and passed an
2616      *         index outside the number of rows of the <code>TableModel</code>
2617      * @see javax.swing.table.TableRowSorter
2618      * @since 1.6
2619      */
2620     public int convertRowIndexToView(int modelRowIndex) {
2621         RowSorter sorter = getRowSorter();
2622         if (sorter != null) {
2623             return sorter.convertRowIndexToView(modelRowIndex);
2624         }
2625         return modelRowIndex;
2626     }
2627 
2628     /**
2629      * Maps the index of the row in terms of the view to the
2630      * underlying <code>TableModel</code>.  If the contents of the
2631      * model are not sorted the model and view indices are the same.
2632      *
2633      * @param viewRowIndex the index of the row in the view
2634      * @return the index of the corresponding row in the model
2635      * @throws IndexOutOfBoundsException if sorting is enabled and passed an
2636      *         index outside the range of the <code>JTable</code> as
2637      *         determined by the method <code>getRowCount</code>
2638      * @see javax.swing.table.TableRowSorter
2639      * @see #getRowCount
2640      * @since 1.6
2641      */
2642     public int convertRowIndexToModel(int viewRowIndex) {
2643         RowSorter sorter = getRowSorter();
2644         if (sorter != null) {
2645             return sorter.convertRowIndexToModel(viewRowIndex);
2646         }
2647         return viewRowIndex;
2648     }
2649 
2650     /**
2651      * Returns the number of rows that can be shown in the
2652      * <code>JTable</code>, given unlimited space.  If a
2653      * <code>RowSorter</code> with a filter has been specified, the
2654      * number of rows returned may differ from that of the underlying
2655      * <code>TableModel</code>.
2656      *
2657      * @return the number of rows shown in the <code>JTable</code>
2658      * @see #getColumnCount
2659      */
2660     public int getRowCount() {
2661         RowSorter sorter = getRowSorter();
2662         if (sorter != null) {
2663             return sorter.getViewRowCount();
2664         }
2665         return getModel().getRowCount();
2666     }
2667 
2668     /**
2669      * Returns the number of columns in the column model. Note that this may
2670      * be different from the number of columns in the table model.
2671      *
2672      * @return  the number of columns in the table
2673      * @see #getRowCount
2674      * @see #removeColumn
2675      */
2676     public int getColumnCount() {
2677         return getColumnModel().getColumnCount();
2678     }
2679 
2680     /**
2681      * Returns the name of the column appearing in the view at
2682      * column position <code>column</code>.
2683      *
2684      * @param  column    the column in the view being queried
2685      * @return the name of the column at position <code>column</code>
2686                         in the view where the first column is column 0
2687      */
2688     public String getColumnName(int column) {
2689         return getModel().getColumnName(convertColumnIndexToModel(column));
2690     }
2691 
2692     /**
2693      * Returns the type of the column appearing in the view at
2694      * column position <code>column</code>.
2695      *
2696      * @param   column   the column in the view being queried
2697      * @return the type of the column at position <code>column</code>
2698      *          in the view where the first column is column 0
2699      */
2700     public Class<?> getColumnClass(int column) {
2701         return getModel().getColumnClass(convertColumnIndexToModel(column));
2702     }
2703 
2704     /**
2705      * Returns the cell value at <code>row</code> and <code>column</code>.
2706      * <p>
2707      * <b>Note</b>: The column is specified in the table view's display
2708      *              order, and not in the <code>TableModel</code>'s column
2709      *              order.  This is an important distinction because as the
2710      *              user rearranges the columns in the table,
2711      *              the column at a given index in the view will change.
2712      *              Meanwhile the user's actions never affect the model's
2713      *              column ordering.
2714      *
2715      * @param   row             the row whose value is to be queried
2716      * @param   column          the column whose value is to be queried
2717      * @return  the Object at the specified cell
2718      */
2719     public Object getValueAt(int row, int column) {
2720         return getModel().getValueAt(convertRowIndexToModel(row),
2721                                      convertColumnIndexToModel(column));
2722     }
2723 
2724     /**
2725      * Sets the value for the cell in the table model at <code>row</code>
2726      * and <code>column</code>.
2727      * <p>
2728      * <b>Note</b>: The column is specified in the table view's display
2729      *              order, and not in the <code>TableModel</code>'s column
2730      *              order.  This is an important distinction because as the
2731      *              user rearranges the columns in the table,
2732      *              the column at a given index in the view will change.
2733      *              Meanwhile the user's actions never affect the model's
2734      *              column ordering.
2735      *
2736      * <code>aValue</code> is the new value.
2737      *
2738      * @param   aValue          the new value
2739      * @param   row             the row of the cell to be changed
2740      * @param   column          the column of the cell to be changed
2741      * @see #getValueAt
2742      */
2743     public void setValueAt(Object aValue, int row, int column) {
2744         getModel().setValueAt(aValue, convertRowIndexToModel(row),
2745                               convertColumnIndexToModel(column));
2746     }
2747 
2748     /**
2749      * Returns true if the cell at <code>row</code> and <code>column</code>
2750      * is editable.  Otherwise, invoking <code>setValueAt</code> on the cell
2751      * will have no effect.
2752      * <p>
2753      * <b>Note</b>: The column is specified in the table view's display
2754      *              order, and not in the <code>TableModel</code>'s column
2755      *              order.  This is an important distinction because as the
2756      *              user rearranges the columns in the table,
2757      *              the column at a given index in the view will change.
2758      *              Meanwhile the user's actions never affect the model's
2759      *              column ordering.
2760      *
2761      *
2762      * @param   row      the row whose value is to be queried
2763      * @param   column   the column whose value is to be queried
2764      * @return  true if the cell is editable
2765      * @see #setValueAt
2766      */
2767     public boolean isCellEditable(int row, int column) {
2768         return getModel().isCellEditable(convertRowIndexToModel(row),
2769                                          convertColumnIndexToModel(column));
2770     }
2771 //
2772 // Adding and removing columns in the view
2773 //
2774 
2775     /**
2776      *  Appends <code>aColumn</code> to the end of the array of columns held by
2777      *  this <code>JTable</code>'s column model.
2778      *  If the column name of <code>aColumn</code> is <code>null</code>,
2779      *  sets the column name of <code>aColumn</code> to the name
2780      *  returned by <code>getModel().getColumnName()</code>.
2781      *  <p>
2782      *  To add a column to this <code>JTable</code> to display the
2783      *  <code>modelColumn</code>'th column of data in the model with a
2784      *  given <code>width</code>, <code>cellRenderer</code>,
2785      *  and <code>cellEditor</code> you can use:
2786      *  <pre>
2787      *
2788      *      addColumn(new TableColumn(modelColumn, width, cellRenderer, cellEditor));
2789      *
2790      *  </pre>
2791      *  [Any of the <code>TableColumn</code> constructors can be used
2792      *  instead of this one.]
2793      *  The model column number is stored inside the <code>TableColumn</code>
2794      *  and is used during rendering and editing to locate the appropriates
2795      *  data values in the model. The model column number does not change
2796      *  when columns are reordered in the view.
2797      *
2798      *  @param  aColumn         the <code>TableColumn</code> to be added
2799      *  @see    #removeColumn
2800      */
2801     public void addColumn(TableColumn aColumn) {
2802         if (aColumn.getHeaderValue() == null) {
2803             int modelColumn = aColumn.getModelIndex();
2804             String columnName = getModel().getColumnName(modelColumn);
2805             aColumn.setHeaderValue(columnName);
2806         }
2807         getColumnModel().addColumn(aColumn);
2808     }
2809 
2810     /**
2811      *  Removes <code>aColumn</code> from this <code>JTable</code>'s
2812      *  array of columns.  Note: this method does not remove the column
2813      *  of data from the model; it just removes the <code>TableColumn</code>
2814      *  that was responsible for displaying it.
2815      *
2816      *  @param  aColumn         the <code>TableColumn</code> to be removed
2817      *  @see    #addColumn
2818      */
2819     public void removeColumn(TableColumn aColumn) {
2820         getColumnModel().removeColumn(aColumn);
2821     }
2822 
2823     /**
2824      * Moves the column <code>column</code> to the position currently
2825      * occupied by the column <code>targetColumn</code> in the view.
2826      * The old column at <code>targetColumn</code> is
2827      * shifted left or right to make room.
2828      *
2829      * @param   column                  the index of column to be moved
2830      * @param   targetColumn            the new index of the column
2831      */
2832     public void moveColumn(int column, int targetColumn) {
2833         getColumnModel().moveColumn(column, targetColumn);
2834     }
2835 
2836 //
2837 // Cover methods for various models and helper methods
2838 //
2839 
2840     /**
2841      * Returns the index of the column that <code>point</code> lies in,
2842      * or -1 if the result is not in the range
2843      * [0, <code>getColumnCount()</code>-1].
2844      *
2845      * @param   point   the location of interest
2846      * @return  the index of the column that <code>point</code> lies in,
2847      *          or -1 if the result is not in the range
2848      *          [0, <code>getColumnCount()</code>-1]
2849      * @see     #rowAtPoint
2850      */
2851     public int columnAtPoint(Point point) {
2852         int x = point.x;
2853         if( !getComponentOrientation().isLeftToRight() ) {
2854             x = getWidth() - x - 1;
2855         }
2856         return getColumnModel().getColumnIndexAtX(x);
2857     }
2858 
2859     /**
2860      * Returns the index of the row that <code>point</code> lies in,
2861      * or -1 if the result is not in the range
2862      * [0, <code>getRowCount()</code>-1].
2863      *
2864      * @param   point   the location of interest
2865      * @return  the index of the row that <code>point</code> lies in,
2866      *          or -1 if the result is not in the range
2867      *          [0, <code>getRowCount()</code>-1]
2868      * @see     #columnAtPoint
2869      */
2870     public int rowAtPoint(Point point) {
2871         int y = point.y;
2872         int result = (rowModel == null) ?  y/getRowHeight() : rowModel.getIndex(y);
2873         if (result < 0) {
2874             return -1;
2875         }
2876         else if (result >= getRowCount()) {
2877             return -1;
2878         }
2879         else {
2880             return result;
2881         }
2882     }
2883 
2884     /**
2885      * Returns a rectangle for the cell that lies at the intersection of
2886      * <code>row</code> and <code>column</code>.
2887      * If <code>includeSpacing</code> is true then the value returned
2888      * has the full height and width of the row and column
2889      * specified. If it is false, the returned rectangle is inset by the
2890      * intercell spacing to return the true bounds of the rendering or
2891      * editing component as it will be set during rendering.
2892      * <p>
2893      * If the column index is valid but the row index is less
2894      * than zero the method returns a rectangle with the
2895      * <code>y</code> and <code>height</code> values set appropriately
2896      * and the <code>x</code> and <code>width</code> values both set
2897      * to zero. In general, when either the row or column indices indicate a
2898      * cell outside the appropriate range, the method returns a rectangle
2899      * depicting the closest edge of the closest cell that is within
2900      * the table's range. When both row and column indices are out
2901      * of range the returned rectangle covers the closest
2902      * point of the closest cell.
2903      * <p>
2904      * In all cases, calculations that use this method to calculate
2905      * results along one axis will not fail because of anomalies in
2906      * calculations along the other axis. When the cell is not valid
2907      * the <code>includeSpacing</code> parameter is ignored.
2908      *
2909      * @param   row                   the row index where the desired cell
2910      *                                is located
2911      * @param   column                the column index where the desired cell
2912      *                                is located in the display; this is not
2913      *                                necessarily the same as the column index
2914      *                                in the data model for the table; the
2915      *                                {@link #convertColumnIndexToView(int)}
2916      *                                method may be used to convert a data
2917      *                                model column index to a display
2918      *                                column index
2919      * @param   includeSpacing        if false, return the true cell bounds -
2920      *                                computed by subtracting the intercell
2921      *                                spacing from the height and widths of
2922      *                                the column and row models
2923      *
2924      * @return  the rectangle containing the cell at location
2925      *          <code>row</code>,<code>column</code>
2926      * @see #getIntercellSpacing
2927      */
2928     public Rectangle getCellRect(int row, int column, boolean includeSpacing) {
2929         Rectangle r = new Rectangle();
2930         boolean valid = true;
2931         if (row < 0) {
2932             // y = height = 0;
2933             valid = false;
2934         }
2935         else if (row >= getRowCount()) {
2936             r.y = getHeight();
2937             valid = false;
2938         }
2939         else {
2940             r.height = getRowHeight(row);
2941             r.y = (rowModel == null) ? row * r.height : rowModel.getPosition(row);
2942         }
2943 
2944         if (column < 0) {
2945             if( !getComponentOrientation().isLeftToRight() ) {
2946                 r.x = getWidth();
2947             }
2948             // otherwise, x = width = 0;
2949             valid = false;
2950         }
2951         else if (column >= getColumnCount()) {
2952             if( getComponentOrientation().isLeftToRight() ) {
2953                 r.x = getWidth();
2954             }
2955             // otherwise, x = width = 0;
2956             valid = false;
2957         }
2958         else {
2959             TableColumnModel cm = getColumnModel();
2960             if( getComponentOrientation().isLeftToRight() ) {
2961                 for(int i = 0; i < column; i++) {
2962                     r.x += cm.getColumn(i).getWidth();
2963                 }
2964             } else {
2965                 for(int i = cm.getColumnCount()-1; i > column; i--) {
2966                     r.x += cm.getColumn(i).getWidth();
2967                 }
2968             }
2969             r.width = cm.getColumn(column).getWidth();
2970         }
2971 
2972         if (valid && !includeSpacing) {
2973             // Bound the margins by their associated dimensions to prevent
2974             // returning bounds with negative dimensions.
2975             int rm = Math.min(getRowMargin(), r.height);
2976             int cm = Math.min(getColumnModel().getColumnMargin(), r.width);
2977             // This is not the same as grow(), it rounds differently.
2978             r.setBounds(r.x + cm/2, r.y + rm/2, r.width - cm, r.height - rm);
2979         }
2980         return r;
2981     }
2982 
2983     private int viewIndexForColumn(TableColumn aColumn) {
2984         TableColumnModel cm = getColumnModel();
2985         for (int column = 0; column < cm.getColumnCount(); column++) {
2986             if (cm.getColumn(column) == aColumn) {
2987                 return column;
2988             }
2989         }
2990         return -1;
2991     }
2992 
2993     /**
2994      * Causes this table to lay out its rows and columns.  Overridden so
2995      * that columns can be resized to accommodate a change in the size of
2996      * a containing parent.
2997      * Resizes one or more of the columns in the table
2998      * so that the total width of all of this <code>JTable</code>'s
2999      * columns is equal to the width of the table.
3000      * <p>
3001      * Before the layout begins the method gets the
3002      * <code>resizingColumn</code> of the <code>tableHeader</code>.
3003      * When the method is called as a result of the resizing of an enclosing window,
3004      * the <code>resizingColumn</code> is <code>null</code>. This means that resizing
3005      * has taken place "outside" the <code>JTable</code> and the change -
3006      * or "delta" - should be distributed to all of the columns regardless
3007      * of this <code>JTable</code>'s automatic resize mode.
3008      * <p>
3009      * If the <code>resizingColumn</code> is not <code>null</code>, it is one of
3010      * the columns in the table that has changed size rather than
3011      * the table itself. In this case the auto-resize modes govern
3012      * the way the extra (or deficit) space is distributed
3013      * amongst the available columns.
3014      * <p>
3015      * The modes are:
3016      * <ul>
3017      * <li>  AUTO_RESIZE_OFF: Don't automatically adjust the column's
3018      * widths at all. Use a horizontal scrollbar to accommodate the
3019      * columns when their sum exceeds the width of the
3020      * <code>Viewport</code>.  If the <code>JTable</code> is not
3021      * enclosed in a <code>JScrollPane</code> this may
3022      * leave parts of the table invisible.
3023      * <li>  AUTO_RESIZE_NEXT_COLUMN: Use just the column after the
3024      * resizing column. This results in the "boundary" or divider
3025      * between adjacent cells being independently adjustable.
3026      * <li>  AUTO_RESIZE_SUBSEQUENT_COLUMNS: Use all columns after the
3027      * one being adjusted to absorb the changes.  This is the
3028      * default behavior.
3029      * <li>  AUTO_RESIZE_LAST_COLUMN: Automatically adjust the
3030      * size of the last column only. If the bounds of the last column
3031      * prevent the desired size from being allocated, set the
3032      * width of the last column to the appropriate limit and make
3033      * no further adjustments.
3034      * <li>  AUTO_RESIZE_ALL_COLUMNS: Spread the delta amongst all the columns
3035      * in the <code>JTable</code>, including the one that is being
3036      * adjusted.
3037      * </ul>
3038      * <p>
3039      * <b>Note:</b> When a <code>JTable</code> makes adjustments
3040      *   to the widths of the columns it respects their minimum and
3041      *   maximum values absolutely.  It is therefore possible that,
3042      *   even after this method is called, the total width of the columns
3043      *   is still not equal to the width of the table. When this happens
3044      *   the <code>JTable</code> does not put itself
3045      *   in AUTO_RESIZE_OFF mode to bring up a scroll bar, or break other
3046      *   commitments of its current auto-resize mode -- instead it
3047      *   allows its bounds to be set larger (or smaller) than the total of the
3048      *   column minimum or maximum, meaning, either that there
3049      *   will not be enough room to display all of the columns, or that the
3050      *   columns will not fill the <code>JTable</code>'s bounds.
3051      *   These respectively, result in the clipping of some columns
3052      *   or an area being painted in the <code>JTable</code>'s
3053      *   background color during painting.
3054      * <p>
3055      *   The mechanism for distributing the delta amongst the available
3056      *   columns is provided in a private method in the <code>JTable</code>
3057      *   class:
3058      * <pre>
3059      *   adjustSizes(long targetSize, final Resizable3 r, boolean inverse)
3060      * </pre>
3061      *   an explanation of which is provided in the following section.
3062      *   <code>Resizable3</code> is a private
3063      *   interface that allows any data structure containing a collection
3064      *   of elements with a size, preferred size, maximum size and minimum size
3065      *   to have its elements manipulated by the algorithm.
3066      *
3067      * <H3> Distributing the delta </H3>
3068      *
3069      * <H4> Overview </H4>
3070      * <P>
3071      * Call "DELTA" the difference between the target size and the
3072      * sum of the preferred sizes of the elements in r. The individual
3073      * sizes are calculated by taking the original preferred
3074      * sizes and adding a share of the DELTA - that share being based on
3075      * how far each preferred size is from its limiting bound (minimum or
3076      * maximum).
3077      *
3078      * <H4>Definition</H4>
3079      * <P>
3080      * Call the individual constraints min[i], max[i], and pref[i].
3081      * <p>
3082      * Call their respective sums: MIN, MAX, and PREF.
3083      * <p>
3084      * Each new size will be calculated using:
3085      *
3086      * <pre>
3087      *          size[i] = pref[i] + delta[i]
3088      * </pre>
3089      * where each individual delta[i] is calculated according to:
3090      * <p>
3091      * If (DELTA &lt; 0) we are in shrink mode where:
3092      *
3093      * <PRE>
3094      *                        DELTA
3095      *          delta[i] = ------------ * (pref[i] - min[i])
3096      *                     (PREF - MIN)
3097      * </PRE>
3098      * If (DELTA &gt; 0) we are in expand mode where:
3099      *
3100      * <PRE>
3101      *                        DELTA
3102      *          delta[i] = ------------ * (max[i] - pref[i])
3103      *                      (MAX - PREF)
3104      * </PRE>
3105      * <P>
3106      * The overall effect is that the total size moves that same percentage,
3107      * k, towards the total minimum or maximum and that percentage guarantees
3108      * accommodation of the required space, DELTA.
3109      *
3110      * <H4>Details</H4>
3111      * <P>
3112      * Naive evaluation of the formulae presented here would be subject to
3113      * the aggregated rounding errors caused by doing this operation in finite
3114      * precision (using ints). To deal with this, the multiplying factor above,
3115      * is constantly recalculated and this takes account of the rounding
3116      * errors in the previous iterations. The result is an algorithm that
3117      * produces a set of integers whose values exactly sum to the supplied
3118      * <code>targetSize</code>, and does so by spreading the rounding
3119      * errors evenly over the given elements.
3120      *
3121      * <H4>When the MAX and MIN bounds are hit</H4>
3122      * <P>
3123      * When <code>targetSize</code> is outside the [MIN, MAX] range,
3124      * the algorithm sets all sizes to their appropriate limiting value
3125      * (maximum or minimum).
3126      *
3127      */
3128     public void doLayout() {
3129         TableColumn resizingColumn = getResizingColumn();
3130         if (resizingColumn == null) {
3131             setWidthsFromPreferredWidths(false);
3132         }
3133         else {
3134             // JTable behaves like a layout manger - but one in which the
3135             // user can come along and dictate how big one of the children
3136             // (columns) is supposed to be.
3137 
3138             // A column has been resized and JTable may need to distribute
3139             // any overall delta to other columns, according to the resize mode.
3140             int columnIndex = viewIndexForColumn(resizingColumn);
3141             int delta = getWidth() - getColumnModel().getTotalColumnWidth();
3142             accommodateDelta(columnIndex, delta);
3143             delta = getWidth() - getColumnModel().getTotalColumnWidth();
3144 
3145             // If the delta cannot be completely accomodated, then the
3146             // resizing column will have to take any remainder. This means
3147             // that the column is not being allowed to take the requested
3148             // width. This happens under many circumstances: For example,
3149             // AUTO_RESIZE_NEXT_COLUMN specifies that any delta be distributed
3150             // to the column after the resizing column. If one were to attempt
3151             // to resize the last column of the table, there would be no
3152             // columns after it, and hence nowhere to distribute the delta.
3153             // It would then be given entirely back to the resizing column,
3154             // preventing it from changing size.
3155             if (delta != 0) {
3156                 resizingColumn.setWidth(resizingColumn.getWidth() + delta);
3157             }
3158 
3159             // At this point the JTable has to work out what preferred sizes
3160             // would have resulted in the layout the user has chosen.
3161             // Thereafter, during window resizing etc. it has to work off
3162             // the preferred sizes as usual - the idea being that, whatever
3163             // the user does, everything stays in synch and things don't jump
3164             // around.
3165             setWidthsFromPreferredWidths(true);
3166         }
3167 
3168         super.doLayout();
3169     }
3170 
3171     private TableColumn getResizingColumn() {
3172         return (tableHeader == null) ? null
3173                                      : tableHeader.getResizingColumn();
3174     }
3175 
3176     /**
3177      * Sizes the table columns to fit the available space.
3178      * @deprecated As of Swing version 1.0.3,
3179      * replaced by <code>doLayout()</code>.
3180      * @see #doLayout
3181      */
3182     @Deprecated
3183     public void sizeColumnsToFit(boolean lastColumnOnly) {
3184         int oldAutoResizeMode = autoResizeMode;
3185         setAutoResizeMode(lastColumnOnly ? AUTO_RESIZE_LAST_COLUMN
3186                                          : AUTO_RESIZE_ALL_COLUMNS);
3187         sizeColumnsToFit(-1);
3188         setAutoResizeMode(oldAutoResizeMode);
3189     }
3190 
3191     /**
3192      * Obsolete as of Java 2 platform v1.4.  Please use the
3193      * <code>doLayout()</code> method instead.
3194      * @param resizingColumn    the column whose resizing made this adjustment
3195      *                          necessary or -1 if there is no such column
3196      * @see  #doLayout
3197      */
3198     public void sizeColumnsToFit(int resizingColumn) {
3199         if (resizingColumn == -1) {
3200             setWidthsFromPreferredWidths(false);
3201         }
3202         else {
3203             if (autoResizeMode == AUTO_RESIZE_OFF) {
3204                 TableColumn aColumn = getColumnModel().getColumn(resizingColumn);
3205                 aColumn.setPreferredWidth(aColumn.getWidth());
3206             }
3207             else {
3208                 int delta = getWidth() - getColumnModel().getTotalColumnWidth();
3209                 accommodateDelta(resizingColumn, delta);
3210                 setWidthsFromPreferredWidths(true);
3211             }
3212         }
3213     }
3214 
3215     private void setWidthsFromPreferredWidths(final boolean inverse) {
3216         int totalWidth     = getWidth();
3217         int totalPreferred = getPreferredSize().width;
3218         int target = !inverse ? totalWidth : totalPreferred;
3219 
3220         final TableColumnModel cm = columnModel;
3221         Resizable3 r = new Resizable3() {
3222             public int  getElementCount()      { return cm.getColumnCount(); }
3223             public int  getLowerBoundAt(int i) { return cm.getColumn(i).getMinWidth(); }
3224             public int  getUpperBoundAt(int i) { return cm.getColumn(i).getMaxWidth(); }
3225             public int  getMidPointAt(int i)  {
3226                 if (!inverse) {
3227                     return cm.getColumn(i).getPreferredWidth();
3228                 }
3229                 else {
3230                     return cm.getColumn(i).getWidth();
3231                 }
3232             }
3233             public void setSizeAt(int s, int i) {
3234                 if (!inverse) {
3235                     cm.getColumn(i).setWidth(s);
3236                 }
3237                 else {
3238                     cm.getColumn(i).setPreferredWidth(s);
3239                 }
3240             }
3241         };
3242 
3243         adjustSizes(target, r, inverse);
3244     }
3245 
3246 
3247     // Distribute delta over columns, as indicated by the autoresize mode.
3248     private void accommodateDelta(int resizingColumnIndex, int delta) {
3249         int columnCount = getColumnCount();
3250         int from = resizingColumnIndex;
3251         int to;
3252 
3253         // Use the mode to determine how to absorb the changes.
3254         switch(autoResizeMode) {
3255             case AUTO_RESIZE_NEXT_COLUMN:
3256                 from = from + 1;
3257                 to = Math.min(from + 1, columnCount); break;
3258             case AUTO_RESIZE_SUBSEQUENT_COLUMNS:
3259                 from = from + 1;
3260                 to = columnCount; break;
3261             case AUTO_RESIZE_LAST_COLUMN:
3262                 from = columnCount - 1;
3263                 to = from + 1; break;
3264             case AUTO_RESIZE_ALL_COLUMNS:
3265                 from = 0;
3266                 to = columnCount; break;
3267             default:
3268                 return;
3269         }
3270 
3271         final int start = from;
3272         final int end = to;
3273         final TableColumnModel cm = columnModel;
3274         Resizable3 r = new Resizable3() {
3275             public int  getElementCount()       { return end-start; }
3276             public int  getLowerBoundAt(int i)  { return cm.getColumn(i+start).getMinWidth(); }
3277             public int  getUpperBoundAt(int i)  { return cm.getColumn(i+start).getMaxWidth(); }
3278             public int  getMidPointAt(int i)    { return cm.getColumn(i+start).getWidth(); }
3279             public void setSizeAt(int s, int i) {        cm.getColumn(i+start).setWidth(s); }
3280         };
3281 
3282         int totalWidth = 0;
3283         for(int i = from; i < to; i++) {
3284             TableColumn aColumn = columnModel.getColumn(i);
3285             int input = aColumn.getWidth();
3286             totalWidth = totalWidth + input;
3287         }
3288 
3289         adjustSizes(totalWidth + delta, r, false);
3290     }
3291 
3292     private interface Resizable2 {
3293         public int  getElementCount();
3294         public int  getLowerBoundAt(int i);
3295         public int  getUpperBoundAt(int i);
3296         public void setSizeAt(int newSize, int i);
3297     }
3298 
3299     private interface Resizable3 extends Resizable2 {
3300         public int  getMidPointAt(int i);
3301     }
3302 
3303 
3304     private void adjustSizes(long target, final Resizable3 r, boolean inverse) {
3305         int N = r.getElementCount();
3306         long totalPreferred = 0;
3307         for(int i = 0; i < N; i++) {
3308             totalPreferred += r.getMidPointAt(i);
3309         }
3310         Resizable2 s;
3311         if ((target < totalPreferred) == !inverse) {
3312             s = new Resizable2() {
3313                 public int  getElementCount()      { return r.getElementCount(); }
3314                 public int  getLowerBoundAt(int i) { return r.getLowerBoundAt(i); }
3315                 public int  getUpperBoundAt(int i) { return r.getMidPointAt(i); }
3316                 public void setSizeAt(int newSize, int i) { r.setSizeAt(newSize, i); }
3317 
3318             };
3319         }
3320         else {
3321             s = new Resizable2() {
3322                 public int  getElementCount()      { return r.getElementCount(); }
3323                 public int  getLowerBoundAt(int i) { return r.getMidPointAt(i); }
3324                 public int  getUpperBoundAt(int i) { return r.getUpperBoundAt(i); }
3325                 public void setSizeAt(int newSize, int i) { r.setSizeAt(newSize, i); }
3326 
3327             };
3328         }
3329         adjustSizes(target, s, !inverse);
3330     }
3331 
3332     private void adjustSizes(long target, Resizable2 r, boolean limitToRange) {
3333         long totalLowerBound = 0;
3334         long totalUpperBound = 0;
3335         for(int i = 0; i < r.getElementCount(); i++) {
3336             totalLowerBound += r.getLowerBoundAt(i);
3337             totalUpperBound += r.getUpperBoundAt(i);
3338         }
3339 
3340         if (limitToRange) {
3341             target = Math.min(Math.max(totalLowerBound, target), totalUpperBound);
3342         }
3343 
3344         for(int i = 0; i < r.getElementCount(); i++) {
3345             int lowerBound = r.getLowerBoundAt(i);
3346             int upperBound = r.getUpperBoundAt(i);
3347             // Check for zero. This happens when the distribution of the delta
3348             // finishes early due to a series of "fixed" entries at the end.
3349             // In this case, lowerBound == upperBound, for all subsequent terms.
3350             int newSize;
3351             if (totalLowerBound == totalUpperBound) {
3352                 newSize = lowerBound;
3353             }
3354             else {
3355                 double f = (double)(target - totalLowerBound)/(totalUpperBound - totalLowerBound);
3356                 newSize = (int)Math.round(lowerBound+f*(upperBound - lowerBound));
3357                 // We'd need to round manually in an all integer version.
3358                 // size[i] = (int)(((totalUpperBound - target) * lowerBound +
3359                 //     (target - totalLowerBound) * upperBound)/(totalUpperBound-totalLowerBound));
3360             }
3361             r.setSizeAt(newSize, i);
3362             target -= newSize;
3363             totalLowerBound -= lowerBound;
3364             totalUpperBound -= upperBound;
3365         }
3366     }
3367 
3368     /**
3369      * Overrides <code>JComponent</code>'s <code>getToolTipText</code>
3370      * method in order to allow the renderer's tips to be used
3371      * if it has text set.
3372      * <p>
3373      * <b>Note:</b> For <code>JTable</code> to properly display
3374      * tooltips of its renderers
3375      * <code>JTable</code> must be a registered component with the
3376      * <code>ToolTipManager</code>.
3377      * This is done automatically in <code>initializeLocalVars</code>,
3378      * but if at a later point <code>JTable</code> is told
3379      * <code>setToolTipText(null)</code> it will unregister the table
3380      * component, and no tips from renderers will display anymore.
3381      *
3382      * @see JComponent#getToolTipText
3383      */
3384     public String getToolTipText(MouseEvent event) {
3385         String tip = null;
3386         Point p = event.getPoint();
3387 
3388         // Locate the renderer under the event location
3389         int hitColumnIndex = columnAtPoint(p);
3390         int hitRowIndex = rowAtPoint(p);
3391 
3392         if ((hitColumnIndex != -1) && (hitRowIndex != -1)) {
3393             TableCellRenderer renderer = getCellRenderer(hitRowIndex, hitColumnIndex);
3394             Component component = prepareRenderer(renderer, hitRowIndex, hitColumnIndex);
3395 
3396             // Now have to see if the component is a JComponent before
3397             // getting the tip
3398             if (component instanceof JComponent) {
3399                 // Convert the event to the renderer's coordinate system
3400                 Rectangle cellRect = getCellRect(hitRowIndex, hitColumnIndex, false);
3401                 p.translate(-cellRect.x, -cellRect.y);
3402                 MouseEvent newEvent = new MouseEvent(component, event.getID(),
3403                                           event.getWhen(), event.getModifiers(),
3404                                           p.x, p.y,
3405                                           event.getXOnScreen(),
3406                                           event.getYOnScreen(),
3407                                           event.getClickCount(),
3408                                           event.isPopupTrigger(),
3409                                           MouseEvent.NOBUTTON);
3410                 MouseEventAccessor meAccessor = AWTAccessor.getMouseEventAccessor();
3411                 meAccessor.setCausedByTouchEvent(newEvent,
3412                     meAccessor.isCausedByTouchEvent(event));
3413 
3414                 tip = ((JComponent)component).getToolTipText(newEvent);
3415             }
3416         }
3417 
3418         // No tip from the renderer get our own tip
3419         if (tip == null)
3420             tip = getToolTipText();
3421 
3422         return tip;
3423     }
3424 
3425 //
3426 // Editing Support
3427 //
3428 
3429     /**
3430      * Sets whether editors in this JTable get the keyboard focus
3431      * when an editor is activated as a result of the JTable
3432      * forwarding keyboard events for a cell.
3433      * By default, this property is false, and the JTable
3434      * retains the focus unless the cell is clicked.
3435      *
3436      * @param surrendersFocusOnKeystroke true if the editor should get the focus
3437      *          when keystrokes cause the editor to be
3438      *          activated
3439      *
3440      *
3441      * @see #getSurrendersFocusOnKeystroke
3442      * @since 1.4
3443      */
3444     public void setSurrendersFocusOnKeystroke(boolean surrendersFocusOnKeystroke) {
3445         this.surrendersFocusOnKeystroke = surrendersFocusOnKeystroke;
3446     }
3447 
3448     /**
3449      * Returns true if the editor should get the focus
3450      * when keystrokes cause the editor to be activated
3451      *
3452      * @return  true if the editor should get the focus
3453      *          when keystrokes cause the editor to be
3454      *          activated
3455      *
3456      * @see #setSurrendersFocusOnKeystroke
3457      * @since 1.4
3458      */
3459     public boolean getSurrendersFocusOnKeystroke() {
3460         return surrendersFocusOnKeystroke;
3461     }
3462 
3463     /**
3464      * Programmatically starts editing the cell at <code>row</code> and
3465      * <code>column</code>, if those indices are in the valid range, and
3466      * the cell at those indices is editable.
3467      * Note that this is a convenience method for
3468      * <code>editCellAt(int, int, null)</code>.
3469      *
3470      * @param   row                             the row to be edited
3471      * @param   column                          the column to be edited
3472      * @return  false if for any reason the cell cannot be edited,
3473      *                or if the indices are invalid
3474      */
3475     public boolean editCellAt(int row, int column) {
3476         return editCellAt(row, column, null);
3477     }
3478 
3479     /**
3480      * Programmatically starts editing the cell at <code>row</code> and
3481      * <code>column</code>, if those indices are in the valid range, and
3482      * the cell at those indices is editable.
3483      * To prevent the <code>JTable</code> from
3484      * editing a particular table, column or cell value, return false from
3485      * the <code>isCellEditable</code> method in the <code>TableModel</code>
3486      * interface.
3487      *
3488      * @param   row     the row to be edited
3489      * @param   column  the column to be edited
3490      * @param   e       event to pass into <code>shouldSelectCell</code>;
3491      *                  note that as of Java 2 platform v1.2, the call to
3492      *                  <code>shouldSelectCell</code> is no longer made
3493      * @return  false if for any reason the cell cannot be edited,
3494      *                or if the indices are invalid
3495      */
3496     public boolean editCellAt(int row, int column, EventObject e){
3497         if (cellEditor != null && !cellEditor.stopCellEditing()) {
3498             return false;
3499         }
3500 
3501         if (row < 0 || row >= getRowCount() ||
3502             column < 0 || column >= getColumnCount()) {
3503             return false;
3504         }
3505 
3506         if (!isCellEditable(row, column))
3507             return false;
3508 
3509         if (editorRemover == null) {
3510             KeyboardFocusManager fm =
3511                 KeyboardFocusManager.getCurrentKeyboardFocusManager();
3512             editorRemover = new CellEditorRemover(fm);
3513             fm.addPropertyChangeListener("permanentFocusOwner", editorRemover);
3514         }
3515 
3516         TableCellEditor editor = getCellEditor(row, column);
3517         if (editor != null && editor.isCellEditable(e)) {
3518             editorComp = prepareEditor(editor, row, column);
3519             if (editorComp == null) {
3520                 removeEditor();
3521                 return false;
3522             }
3523             editorComp.setBounds(getCellRect(row, column, false));
3524             add(editorComp);
3525             editorComp.validate();
3526             editorComp.repaint();
3527 
3528             setCellEditor(editor);
3529             setEditingRow(row);
3530             setEditingColumn(column);
3531             editor.addCellEditorListener(this);
3532 
3533             return true;
3534         }
3535         return false;
3536     }
3537 
3538     /**
3539      * Returns true if a cell is being edited.
3540      *
3541      * @return  true if the table is editing a cell
3542      * @see     #editingColumn
3543      * @see     #editingRow
3544      */
3545     public boolean isEditing() {
3546         return cellEditor != null;
3547     }
3548 
3549     /**
3550      * Returns the component that is handling the editing session.
3551      * If nothing is being edited, returns null.
3552      *
3553      * @return  Component handling editing session
3554      */
3555     public Component getEditorComponent() {
3556         return editorComp;
3557     }
3558 
3559     /**
3560      * Returns the index of the column that contains the cell currently
3561      * being edited.  If nothing is being edited, returns -1.
3562      *
3563      * @return  the index of the column that contains the cell currently
3564      *          being edited; returns -1 if nothing being edited
3565      * @see #editingRow
3566      */
3567     public int getEditingColumn() {
3568         return editingColumn;
3569     }
3570 
3571     /**
3572      * Returns the index of the row that contains the cell currently
3573      * being edited.  If nothing is being edited, returns -1.
3574      *
3575      * @return  the index of the row that contains the cell currently
3576      *          being edited; returns -1 if nothing being edited
3577      * @see #editingColumn
3578      */
3579     public int getEditingRow() {
3580         return editingRow;
3581     }
3582 
3583 //
3584 // Managing TableUI
3585 //
3586 
3587     /**
3588      * Returns the L&amp;F object that renders this component.
3589      *
3590      * @return the <code>TableUI</code> object that renders this component
3591      */
3592     public TableUI getUI() {
3593         return (TableUI)ui;
3594     }
3595 
3596     /**
3597      * Sets the L&amp;F object that renders this component and repaints.
3598      *
3599      * @param ui  the TableUI L&amp;F object
3600      * @see UIDefaults#getUI
3601      * @beaninfo
3602      *        bound: true
3603      *       hidden: true
3604      *    attribute: visualUpdate true
3605      *  description: The UI object that implements the Component's LookAndFeel.
3606      */
3607     public void setUI(TableUI ui) {
3608         if (this.ui != ui) {
3609             super.setUI(ui);
3610             repaint();
3611         }
3612     }
3613 
3614     /**
3615      * Notification from the <code>UIManager</code> that the L&amp;F has changed.
3616      * Replaces the current UI object with the latest version from the
3617      * <code>UIManager</code>.
3618      *
3619      * @see JComponent#updateUI
3620      */
3621     public void updateUI() {
3622         // Update the UIs of the cell renderers, cell editors and header renderers.
3623         TableColumnModel cm = getColumnModel();
3624         for(int column = 0; column < cm.getColumnCount(); column++) {
3625             TableColumn aColumn = cm.getColumn(column);
3626             SwingUtilities.updateRendererOrEditorUI(aColumn.getCellRenderer());
3627             SwingUtilities.updateRendererOrEditorUI(aColumn.getCellEditor());
3628             SwingUtilities.updateRendererOrEditorUI(aColumn.getHeaderRenderer());
3629         }
3630 
3631         // Update the UIs of all the default renderers.
3632         Enumeration defaultRenderers = defaultRenderersByColumnClass.elements();
3633         while (defaultRenderers.hasMoreElements()) {
3634             SwingUtilities.updateRendererOrEditorUI(defaultRenderers.nextElement());
3635         }
3636 
3637         // Update the UIs of all the default editors.
3638         Enumeration defaultEditors = defaultEditorsByColumnClass.elements();
3639         while (defaultEditors.hasMoreElements()) {
3640             SwingUtilities.updateRendererOrEditorUI(defaultEditors.nextElement());
3641         }
3642 
3643         // Update the UI of the table header
3644         if (tableHeader != null && tableHeader.getParent() == null) {
3645             tableHeader.updateUI();
3646         }
3647 
3648         // Update UI applied to parent ScrollPane
3649         configureEnclosingScrollPaneUI();
3650 
3651         setUI((TableUI)UIManager.getUI(this));
3652     }
3653 
3654     /**
3655      * Returns the suffix used to construct the name of the L&amp;F class used to
3656      * render this component.
3657      *
3658      * @return the string "TableUI"
3659      * @see JComponent#getUIClassID
3660      * @see UIDefaults#getUI
3661      */
3662     public String getUIClassID() {
3663         return uiClassID;
3664     }
3665 
3666 
3667 //
3668 // Managing models
3669 //
3670 
3671     /**
3672      * Sets the data model for this table to <code>newModel</code> and registers
3673      * with it for listener notifications from the new data model.
3674      *
3675      * @param   dataModel        the new data source for this table
3676      * @exception IllegalArgumentException      if <code>newModel</code> is <code>null</code>
3677      * @see     #getModel
3678      * @beaninfo
3679      *  bound: true
3680      *  description: The model that is the source of the data for this view.
3681      */
3682     public void setModel(TableModel dataModel) {
3683         if (dataModel == null) {
3684             throw new IllegalArgumentException("Cannot set a null TableModel");
3685         }
3686         if (this.dataModel != dataModel) {
3687             TableModel old = this.dataModel;
3688             if (old != null) {
3689                 old.removeTableModelListener(this);
3690             }
3691             this.dataModel = dataModel;
3692             dataModel.addTableModelListener(this);
3693 
3694             tableChanged(new TableModelEvent(dataModel, TableModelEvent.HEADER_ROW));
3695 
3696             firePropertyChange("model", old, dataModel);
3697 
3698             if (getAutoCreateRowSorter()) {
3699                 setRowSorter(new TableRowSorter<TableModel>(dataModel));
3700             }
3701         }
3702     }
3703 
3704     /**
3705      * Returns the <code>TableModel</code> that provides the data displayed by this
3706      * <code>JTable</code>.
3707      *
3708      * @return  the <code>TableModel</code> that provides the data displayed by this <code>JTable</code>
3709      * @see     #setModel
3710      */
3711     public TableModel getModel() {
3712         return dataModel;
3713     }
3714 
3715     /**
3716      * Sets the column model for this table to <code>newModel</code> and registers
3717      * for listener notifications from the new column model. Also sets
3718      * the column model of the <code>JTableHeader</code> to <code>columnModel</code>.
3719      *
3720      * @param   columnModel        the new data source for this table
3721      * @exception IllegalArgumentException      if <code>columnModel</code> is <code>null</code>
3722      * @see     #getColumnModel
3723      * @beaninfo
3724      *  bound: true
3725      *  description: The object governing the way columns appear in the view.
3726      */
3727     public void setColumnModel(TableColumnModel columnModel) {
3728         if (columnModel == null) {
3729             throw new IllegalArgumentException("Cannot set a null ColumnModel");
3730         }
3731         TableColumnModel old = this.columnModel;
3732         if (columnModel != old) {
3733             if (old != null) {
3734                 old.removeColumnModelListener(this);
3735             }
3736             this.columnModel = columnModel;
3737             columnModel.addColumnModelListener(this);
3738 
3739             // Set the column model of the header as well.
3740             if (tableHeader != null) {
3741                 tableHeader.setColumnModel(columnModel);
3742             }
3743 
3744             firePropertyChange("columnModel", old, columnModel);
3745             resizeAndRepaint();
3746         }
3747     }
3748 
3749     /**
3750      * Returns the <code>TableColumnModel</code> that contains all column information
3751      * of this table.
3752      *
3753      * @return  the object that provides the column state of the table
3754      * @see     #setColumnModel
3755      */
3756     public TableColumnModel getColumnModel() {
3757         return columnModel;
3758     }
3759 
3760     /**
3761      * Sets the row selection model for this table to <code>newModel</code>
3762      * and registers for listener notifications from the new selection model.
3763      *
3764      * @param   newModel        the new selection model
3765      * @exception IllegalArgumentException      if <code>newModel</code> is <code>null</code>
3766      * @see     #getSelectionModel
3767      * @beaninfo
3768      *      bound: true
3769      *      description: The selection model for rows.
3770      */
3771     public void setSelectionModel(ListSelectionModel newModel) {
3772         if (newModel == null) {
3773             throw new IllegalArgumentException("Cannot set a null SelectionModel");
3774         }
3775 
3776         ListSelectionModel oldModel = selectionModel;
3777 
3778         if (newModel != oldModel) {
3779             if (oldModel != null) {
3780                 oldModel.removeListSelectionListener(this);
3781             }
3782 
3783             selectionModel = newModel;
3784             newModel.addListSelectionListener(this);
3785 
3786             firePropertyChange("selectionModel", oldModel, newModel);
3787             repaint();
3788         }
3789     }
3790 
3791     /**
3792      * Returns the <code>ListSelectionModel</code> that is used to maintain row
3793      * selection state.
3794      *
3795      * @return  the object that provides row selection state, <code>null</code>
3796      *          if row selection is not allowed
3797      * @see     #setSelectionModel
3798      */
3799     public ListSelectionModel getSelectionModel() {
3800         return selectionModel;
3801     }
3802 
3803 //
3804 // RowSorterListener
3805 //
3806 
3807     /**
3808      * <code>RowSorterListener</code> notification that the
3809      * <code>RowSorter</code> has changed in some way.
3810      *
3811      * @param e the <code>RowSorterEvent</code> describing the change
3812      * @throws NullPointerException if <code>e</code> is <code>null</code>
3813      * @since 1.6
3814      */
3815     public void sorterChanged(RowSorterEvent e) {
3816         if (e.getType() == RowSorterEvent.Type.SORT_ORDER_CHANGED) {
3817             JTableHeader header = getTableHeader();
3818             if (header != null) {
3819                 header.repaint();
3820             }
3821         }
3822         else if (e.getType() == RowSorterEvent.Type.SORTED) {
3823             sorterChanged = true;
3824             if (!ignoreSortChange) {
3825                 sortedTableChanged(e, null);
3826             }
3827         }
3828     }
3829 
3830 
3831     /**
3832      * SortManager provides support for managing the selection and variable
3833      * row heights when sorting is enabled. This information is encapsulated
3834      * into a class to avoid bulking up JTable.
3835      */
3836     private final class SortManager {
3837         RowSorter<? extends TableModel> sorter;
3838 
3839         // Selection, in terms of the model. This is lazily created
3840         // as needed.
3841         private ListSelectionModel modelSelection;
3842         private int modelLeadIndex;
3843         // Set to true while in the process of changing the selection.
3844         // If this is true the selection change is ignored.
3845         private boolean syncingSelection;
3846         // Temporary cache of selection, in terms of model. This is only used
3847         // if we don't need the full weight of modelSelection.
3848         private int[] lastModelSelection;
3849 
3850         // Heights of the rows in terms of the model.
3851         private SizeSequence modelRowSizes;
3852 
3853 
3854         SortManager(RowSorter<? extends TableModel> sorter) {
3855             this.sorter = sorter;
3856             sorter.addRowSorterListener(JTable.this);
3857         }
3858 
3859         /**
3860          * Disposes any resources used by this SortManager.
3861          */
3862         public void dispose() {
3863             if (sorter != null) {
3864                 sorter.removeRowSorterListener(JTable.this);
3865             }
3866         }
3867 
3868         /**
3869          * Sets the height for a row at a specified index.
3870          */
3871         public void setViewRowHeight(int viewIndex, int rowHeight) {
3872             if (modelRowSizes == null) {
3873                 modelRowSizes = new SizeSequence(getModel().getRowCount(),
3874                                                  getRowHeight());
3875             }
3876             modelRowSizes.setSize(convertRowIndexToModel(viewIndex),rowHeight);
3877         }
3878 
3879         /**
3880          * Invoked when the underlying model has completely changed.
3881          */
3882         public void allChanged() {
3883             modelLeadIndex = -1;
3884             modelSelection = null;
3885             modelRowSizes = null;
3886         }
3887 
3888         /**
3889          * Invoked when the selection, on the view, has changed.
3890          */
3891         public void viewSelectionChanged(ListSelectionEvent e) {
3892             if (!syncingSelection && modelSelection != null) {
3893                 modelSelection = null;
3894             }
3895         }
3896 
3897         /**
3898          * Invoked when either the table model has changed, or the RowSorter
3899          * has changed. This is invoked prior to notifying the sorter of the
3900          * change.
3901          */
3902         public void prepareForChange(RowSorterEvent sortEvent,
3903                                      ModelChange change) {
3904             if (getUpdateSelectionOnSort()) {
3905                 cacheSelection(sortEvent, change);
3906             }
3907         }
3908 
3909         /**
3910          * Updates the internal cache of the selection based on the change.
3911          */
3912         private void cacheSelection(RowSorterEvent sortEvent,
3913                                     ModelChange change) {
3914             if (sortEvent != null) {
3915                 // sort order changed. If modelSelection is null and filtering
3916                 // is enabled we need to cache the selection in terms of the
3917                 // underlying model, this will allow us to correctly restore
3918                 // the selection even if rows are filtered out.
3919                 if (modelSelection == null &&
3920                         sorter.getViewRowCount() != getModel().getRowCount()) {
3921                     modelSelection = new DefaultListSelectionModel();
3922                     ListSelectionModel viewSelection = getSelectionModel();
3923                     int min = viewSelection.getMinSelectionIndex();
3924                     int max = viewSelection.getMaxSelectionIndex();
3925                     int modelIndex;
3926                     for (int viewIndex = min; viewIndex <= max; viewIndex++) {
3927                         if (viewSelection.isSelectedIndex(viewIndex)) {
3928                             modelIndex = convertRowIndexToModel(
3929                                     sortEvent, viewIndex);
3930                             if (modelIndex != -1) {
3931                                 modelSelection.addSelectionInterval(
3932                                     modelIndex, modelIndex);
3933                             }
3934                         }
3935                     }
3936                     modelIndex = convertRowIndexToModel(sortEvent,
3937                             viewSelection.getLeadSelectionIndex());
3938                     SwingUtilities2.setLeadAnchorWithoutSelection(
3939                             modelSelection, modelIndex, modelIndex);
3940                 } else if (modelSelection == null) {
3941                     // Sorting changed, haven't cached selection in terms
3942                     // of model and no filtering. Temporarily cache selection.
3943                     cacheModelSelection(sortEvent);
3944                 }
3945             } else if (change.allRowsChanged) {
3946                 // All the rows have changed, chuck any cached selection.
3947                 modelSelection = null;
3948             } else if (modelSelection != null) {
3949                 // Table changed, reflect changes in cached selection model.
3950                 switch(change.type) {
3951                 case TableModelEvent.DELETE:
3952                     modelSelection.removeIndexInterval(change.startModelIndex,
3953                                                        change.endModelIndex);
3954                     break;
3955                 case TableModelEvent.INSERT:
3956                     modelSelection.insertIndexInterval(change.startModelIndex,
3957                                                        change.length,
3958                                                        true);
3959                     break;
3960                 default:
3961                     break;
3962                 }
3963             } else {
3964                 // table changed, but haven't cached rows, temporarily
3965                 // cache them.
3966                 cacheModelSelection(null);
3967             }
3968         }
3969 
3970         private void cacheModelSelection(RowSorterEvent sortEvent) {
3971             lastModelSelection = convertSelectionToModel(sortEvent);
3972             modelLeadIndex = convertRowIndexToModel(sortEvent,
3973                         selectionModel.getLeadSelectionIndex());
3974         }
3975 
3976         /**
3977          * Inovked when either the table has changed or the sorter has changed
3978          * and after the sorter has been notified. If necessary this will
3979          * reapply the selection and variable row heights.
3980          */
3981         public void processChange(RowSorterEvent sortEvent,
3982                                   ModelChange change,
3983                                   boolean sorterChanged) {
3984             if (change != null) {
3985                 if (change.allRowsChanged) {
3986                     modelRowSizes = null;
3987                     rowModel = null;
3988                 } else if (modelRowSizes != null) {
3989                     if (change.type == TableModelEvent.INSERT) {
3990                         modelRowSizes.insertEntries(change.startModelIndex,
3991                                                     change.endModelIndex -
3992                                                     change.startModelIndex + 1,
3993                                                     getRowHeight());
3994                     } else if (change.type == TableModelEvent.DELETE) {
3995                         modelRowSizes.removeEntries(change.startModelIndex,
3996                                                     change.endModelIndex -
3997                                                     change.startModelIndex +1 );
3998                     }
3999                 }
4000             }
4001             if (sorterChanged) {
4002                 setViewRowHeightsFromModel();
4003                 restoreSelection(change);
4004             }
4005         }
4006 
4007         /**
4008          * Resets the variable row heights in terms of the view from
4009          * that of the variable row heights in terms of the model.
4010          */
4011         private void setViewRowHeightsFromModel() {
4012             if (modelRowSizes != null) {
4013                 rowModel.setSizes(getRowCount(), getRowHeight());
4014                 for (int viewIndex = getRowCount() - 1; viewIndex >= 0;
4015                          viewIndex--) {
4016                     int modelIndex = convertRowIndexToModel(viewIndex);
4017                     rowModel.setSize(viewIndex,
4018                                      modelRowSizes.getSize(modelIndex));
4019                 }
4020             }
4021         }
4022 
4023         /**
4024          * Restores the selection from that in terms of the model.
4025          */
4026         private void restoreSelection(ModelChange change) {
4027             syncingSelection = true;
4028             if (lastModelSelection != null) {
4029                 restoreSortingSelection(lastModelSelection,
4030                                         modelLeadIndex, change);
4031                 lastModelSelection = null;
4032             } else if (modelSelection != null) {
4033                 ListSelectionModel viewSelection = getSelectionModel();
4034                 viewSelection.setValueIsAdjusting(true);
4035                 viewSelection.clearSelection();
4036                 int min = modelSelection.getMinSelectionIndex();
4037                 int max = modelSelection.getMaxSelectionIndex();
4038                 int viewIndex;
4039                 for (int modelIndex = min; modelIndex <= max; modelIndex++) {
4040                     if (modelSelection.isSelectedIndex(modelIndex)) {
4041                         viewIndex = convertRowIndexToView(modelIndex);
4042                         if (viewIndex != -1) {
4043                             viewSelection.addSelectionInterval(viewIndex,
4044                                                                viewIndex);
4045                         }
4046                     }
4047                 }
4048                 // Restore the lead
4049                 int viewLeadIndex = modelSelection.getLeadSelectionIndex();
4050                 if (viewLeadIndex != -1 && !modelSelection.isSelectionEmpty()) {
4051                     viewLeadIndex = convertRowIndexToView(viewLeadIndex);
4052                 }
4053                 SwingUtilities2.setLeadAnchorWithoutSelection(
4054                         viewSelection, viewLeadIndex, viewLeadIndex);
4055                 viewSelection.setValueIsAdjusting(false);
4056             }
4057             syncingSelection = false;
4058         }
4059     }
4060 
4061 
4062     /**
4063      * ModelChange is used when sorting to restore state, it corresponds
4064      * to data from a TableModelEvent.  The values are precalculated as
4065      * they are used extensively.
4066      */
4067     private final class ModelChange {
4068         // Starting index of the change, in terms of the model
4069         int startModelIndex;
4070 
4071         // Ending index of the change, in terms of the model
4072         int endModelIndex;
4073 
4074         // Type of change
4075         int type;
4076 
4077         // Number of rows in the model
4078         int modelRowCount;
4079 
4080         // The event that triggered this.
4081         TableModelEvent event;
4082 
4083         // Length of the change (end - start + 1)
4084         int length;
4085 
4086         // True if the event indicates all the contents have changed
4087         boolean allRowsChanged;
4088 
4089         ModelChange(TableModelEvent e) {
4090             startModelIndex = Math.max(0, e.getFirstRow());
4091             endModelIndex = e.getLastRow();
4092             modelRowCount = getModel().getRowCount();
4093             if (endModelIndex < 0) {
4094                 endModelIndex = Math.max(0, modelRowCount - 1);
4095             }
4096             length = endModelIndex - startModelIndex + 1;
4097             type = e.getType();
4098             event = e;
4099             allRowsChanged = (e.getLastRow() == Integer.MAX_VALUE);
4100         }
4101     }
4102 
4103     /**
4104      * Invoked when <code>sorterChanged</code> is invoked, or
4105      * when <code>tableChanged</code> is invoked and sorting is enabled.
4106      */
4107     private void sortedTableChanged(RowSorterEvent sortedEvent,
4108                                     TableModelEvent e) {
4109         int editingModelIndex = -1;
4110         ModelChange change = (e != null) ? new ModelChange(e) : null;
4111 
4112         if ((change == null || !change.allRowsChanged) &&
4113                 this.editingRow != -1) {
4114             editingModelIndex = convertRowIndexToModel(sortedEvent,
4115                                                        this.editingRow);
4116         }
4117 
4118         sortManager.prepareForChange(sortedEvent, change);
4119 
4120         if (e != null) {
4121             if (change.type == TableModelEvent.UPDATE) {
4122                 repaintSortedRows(change);
4123             }
4124             notifySorter(change);
4125             if (change.type != TableModelEvent.UPDATE) {
4126                 // If the Sorter is unsorted we will not have received
4127                 // notification, force treating insert/delete as a change.
4128                 sorterChanged = true;
4129             }
4130         }
4131         else {
4132             sorterChanged = true;
4133         }
4134 
4135         sortManager.processChange(sortedEvent, change, sorterChanged);
4136 
4137         if (sorterChanged) {
4138             // Update the editing row
4139             if (this.editingRow != -1) {
4140                 int newIndex = (editingModelIndex == -1) ? -1 :
4141                         convertRowIndexToView(editingModelIndex,change);
4142                 restoreSortingEditingRow(newIndex);
4143             }
4144 
4145             // And handle the appropriate repainting.
4146             if (e == null || change.type != TableModelEvent.UPDATE) {
4147                 resizeAndRepaint();
4148             }
4149         }
4150 
4151         // Check if lead/anchor need to be reset.
4152         if (change != null && change.allRowsChanged) {
4153             clearSelectionAndLeadAnchor();
4154             resizeAndRepaint();
4155         }
4156     }
4157 
4158     /**
4159      * Repaints the sort of sorted rows in response to a TableModelEvent.
4160      */
4161     private void repaintSortedRows(ModelChange change) {
4162         if (change.startModelIndex > change.endModelIndex ||
4163                 change.startModelIndex + 10 < change.endModelIndex) {
4164             // Too much has changed, punt
4165             repaint();
4166             return;
4167         }
4168         int eventColumn = change.event.getColumn();
4169         int columnViewIndex = eventColumn;
4170         if (columnViewIndex == TableModelEvent.ALL_COLUMNS) {
4171             columnViewIndex = 0;
4172         }
4173         else {
4174             columnViewIndex = convertColumnIndexToView(columnViewIndex);
4175             if (columnViewIndex == -1) {
4176                 return;
4177             }
4178         }
4179         int modelIndex = change.startModelIndex;
4180         while (modelIndex <= change.endModelIndex) {
4181             int viewIndex = convertRowIndexToView(modelIndex++);
4182             if (viewIndex != -1) {
4183                 Rectangle dirty = getCellRect(viewIndex, columnViewIndex,
4184                                               false);
4185                 int x = dirty.x;
4186                 int w = dirty.width;
4187                 if (eventColumn == TableModelEvent.ALL_COLUMNS) {
4188                     x = 0;
4189                     w = getWidth();
4190                 }
4191                 repaint(x, dirty.y, w, dirty.height);
4192             }
4193         }
4194     }
4195 
4196     /**
4197      * Restores the selection after a model event/sort order changes.
4198      * All coordinates are in terms of the model.
4199      */
4200     private void restoreSortingSelection(int[] selection, int lead,
4201             ModelChange change) {
4202         // Convert the selection from model to view
4203         for (int i = selection.length - 1; i >= 0; i--) {
4204             selection[i] = convertRowIndexToView(selection[i], change);
4205         }
4206         lead = convertRowIndexToView(lead, change);
4207 
4208         // Check for the common case of no change in selection for 1 row
4209         if (selection.length == 0 ||
4210             (selection.length == 1 && selection[0] == getSelectedRow())) {
4211             return;
4212         }
4213 
4214         // And apply the new selection
4215         selectionModel.setValueIsAdjusting(true);
4216         selectionModel.clearSelection();
4217         for (int i = selection.length - 1; i >= 0; i--) {
4218             if (selection[i] != -1) {
4219                 selectionModel.addSelectionInterval(selection[i],
4220                                                     selection[i]);
4221             }
4222         }
4223         SwingUtilities2.setLeadAnchorWithoutSelection(
4224                 selectionModel, lead, lead);
4225         selectionModel.setValueIsAdjusting(false);
4226     }
4227 
4228     /**
4229      * Restores the editing row after a model event/sort order change.
4230      *
4231      * @param editingRow new index of the editingRow, in terms of the view
4232      */
4233     private void restoreSortingEditingRow(int editingRow) {
4234         if (editingRow == -1) {
4235             // Editing row no longer being shown, cancel editing
4236             TableCellEditor editor = getCellEditor();
4237             if (editor != null) {
4238                 // First try and cancel
4239                 editor.cancelCellEditing();
4240                 if (getCellEditor() != null) {
4241                     // CellEditor didn't cede control, forcefully
4242                     // remove it
4243                     removeEditor();
4244                 }
4245             }
4246         }
4247         else {
4248             // Repositioning handled in BasicTableUI
4249             this.editingRow = editingRow;
4250             repaint();
4251         }
4252     }
4253 
4254     /**
4255      * Notifies the sorter of a change in the underlying model.
4256      */
4257     private void notifySorter(ModelChange change) {
4258         try {
4259             ignoreSortChange = true;
4260             sorterChanged = false;
4261             switch(change.type) {
4262             case TableModelEvent.UPDATE:
4263                 if (change.event.getLastRow() == Integer.MAX_VALUE) {
4264                     sortManager.sorter.allRowsChanged();
4265                 } else if (change.event.getColumn() ==
4266                            TableModelEvent.ALL_COLUMNS) {
4267                     sortManager.sorter.rowsUpdated(change.startModelIndex,
4268                                        change.endModelIndex);
4269                 } else {
4270                     sortManager.sorter.rowsUpdated(change.startModelIndex,
4271                                        change.endModelIndex,
4272                                        change.event.getColumn());
4273                 }
4274                 break;
4275             case TableModelEvent.INSERT:
4276                 sortManager.sorter.rowsInserted(change.startModelIndex,
4277                                     change.endModelIndex);
4278                 break;
4279             case TableModelEvent.DELETE:
4280                 sortManager.sorter.rowsDeleted(change.startModelIndex,
4281                                    change.endModelIndex);
4282                 break;
4283             }
4284         } finally {
4285             ignoreSortChange = false;
4286         }
4287     }
4288 
4289     /**
4290      * Converts a model index to view index.  This is called when the
4291      * sorter or model changes and sorting is enabled.
4292      *
4293      * @param change describes the TableModelEvent that initiated the change;
4294      *        will be null if called as the result of a sort
4295      */
4296     private int convertRowIndexToView(int modelIndex, ModelChange change) {
4297         if (modelIndex < 0) {
4298             return -1;
4299         }
4300         if (change != null && modelIndex >= change.startModelIndex) {
4301             if (change.type == TableModelEvent.INSERT) {
4302                 if (modelIndex + change.length >= change.modelRowCount) {
4303                     return -1;
4304                 }
4305                 return sortManager.sorter.convertRowIndexToView(
4306                         modelIndex + change.length);
4307             }
4308             else if (change.type == TableModelEvent.DELETE) {
4309                 if (modelIndex <= change.endModelIndex) {
4310                     // deleted
4311                     return -1;
4312                 }
4313                 else {
4314                     if (modelIndex - change.length >= change.modelRowCount) {
4315                         return -1;
4316                     }
4317                     return sortManager.sorter.convertRowIndexToView(
4318                             modelIndex - change.length);
4319                 }
4320             }
4321             // else, updated
4322         }
4323         if (modelIndex >= getModel().getRowCount()) {
4324             return -1;
4325         }
4326         return sortManager.sorter.convertRowIndexToView(modelIndex);
4327     }
4328 
4329     /**
4330      * Converts the selection to model coordinates.  This is used when
4331      * the model changes or the sorter changes.
4332      */
4333     private int[] convertSelectionToModel(RowSorterEvent e) {
4334         int[] selection = getSelectedRows();
4335         for (int i = selection.length - 1; i >= 0; i--) {
4336             selection[i] = convertRowIndexToModel(e, selection[i]);
4337         }
4338         return selection;
4339     }
4340 
4341     private int convertRowIndexToModel(RowSorterEvent e, int viewIndex) {
4342         if (e != null) {
4343             if (e.getPreviousRowCount() == 0) {
4344                 return viewIndex;
4345             }
4346             // range checking handled by RowSorterEvent
4347             return e.convertPreviousRowIndexToModel(viewIndex);
4348         }
4349         // Make sure the viewIndex is valid
4350         if (viewIndex < 0 || viewIndex >= getRowCount()) {
4351             return -1;
4352         }
4353         return convertRowIndexToModel(viewIndex);
4354     }
4355 
4356 //
4357 // Implementing TableModelListener interface
4358 //
4359 
4360     /**
4361      * Invoked when this table's <code>TableModel</code> generates
4362      * a <code>TableModelEvent</code>.
4363      * The <code>TableModelEvent</code> should be constructed in the
4364      * coordinate system of the model; the appropriate mapping to the
4365      * view coordinate system is performed by this <code>JTable</code>
4366      * when it receives the event.
4367      * <p>
4368      * Application code will not use these methods explicitly, they
4369      * are used internally by <code>JTable</code>.
4370      * <p>
4371      * Note that as of 1.3, this method clears the selection, if any.
4372      */
4373     public void tableChanged(TableModelEvent e) {
4374         if (e == null || e.getFirstRow() == TableModelEvent.HEADER_ROW) {
4375             // The whole thing changed
4376             clearSelectionAndLeadAnchor();
4377 
4378             rowModel = null;
4379 
4380             if (sortManager != null) {
4381                 try {
4382                     ignoreSortChange = true;
4383                     sortManager.sorter.modelStructureChanged();
4384                 } finally {
4385                     ignoreSortChange = false;
4386                 }
4387                 sortManager.allChanged();
4388             }
4389 
4390             if (getAutoCreateColumnsFromModel()) {
4391                 // This will effect invalidation of the JTable and JTableHeader.
4392                 createDefaultColumnsFromModel();
4393                 return;
4394             }
4395 
4396             resizeAndRepaint();
4397             return;
4398         }
4399 
4400         if (sortManager != null) {
4401             sortedTableChanged(null, e);
4402             return;
4403         }
4404 
4405         // The totalRowHeight calculated below will be incorrect if
4406         // there are variable height rows. Repaint the visible region,
4407         // but don't return as a revalidate may be necessary as well.
4408         if (rowModel != null) {
4409             repaint();
4410         }
4411 
4412         if (e.getType() == TableModelEvent.INSERT) {
4413             tableRowsInserted(e);
4414             return;
4415         }
4416 
4417         if (e.getType() == TableModelEvent.DELETE) {
4418             tableRowsDeleted(e);
4419             return;
4420         }
4421 
4422         int modelColumn = e.getColumn();
4423         int start = e.getFirstRow();
4424         int end = e.getLastRow();
4425 
4426         Rectangle dirtyRegion;
4427         if (modelColumn == TableModelEvent.ALL_COLUMNS) {
4428             // 1 or more rows changed
4429             dirtyRegion = new Rectangle(0, start * getRowHeight(),
4430                                         getColumnModel().getTotalColumnWidth(), 0);
4431         }
4432         else {
4433             // A cell or column of cells has changed.
4434             // Unlike the rest of the methods in the JTable, the TableModelEvent
4435             // uses the coordinate system of the model instead of the view.
4436             // This is the only place in the JTable where this "reverse mapping"
4437             // is used.
4438             int column = convertColumnIndexToView(modelColumn);
4439             dirtyRegion = getCellRect(start, column, false);
4440         }
4441 
4442         // Now adjust the height of the dirty region according to the value of "end".
4443         // Check for Integer.MAX_VALUE as this will cause an overflow.
4444         if (end != Integer.MAX_VALUE) {
4445             dirtyRegion.height = (end-start+1)*getRowHeight();
4446             repaint(dirtyRegion.x, dirtyRegion.y, dirtyRegion.width, dirtyRegion.height);
4447         }
4448         // In fact, if the end is Integer.MAX_VALUE we need to revalidate anyway
4449         // because the scrollbar may need repainting.
4450         else {
4451             clearSelectionAndLeadAnchor();
4452             resizeAndRepaint();
4453             rowModel = null;
4454         }
4455     }
4456 
4457     /*
4458      * Invoked when rows have been inserted into the table.
4459      * <p>
4460      * Application code will not use these methods explicitly, they
4461      * are used internally by JTable.
4462      *
4463      * @param e the TableModelEvent encapsulating the insertion
4464      */
4465     private void tableRowsInserted(TableModelEvent e) {
4466         int start = e.getFirstRow();
4467         int end = e.getLastRow();
4468         if (start < 0) {
4469             start = 0;
4470         }
4471         if (end < 0) {
4472             end = getRowCount()-1;
4473         }
4474 
4475         // Adjust the selection to account for the new rows.
4476         int length = end - start + 1;
4477         selectionModel.insertIndexInterval(start, length, true);
4478 
4479         // If we have variable height rows, adjust the row model.
4480         if (rowModel != null) {
4481             rowModel.insertEntries(start, length, getRowHeight());
4482         }
4483         int rh = getRowHeight() ;
4484         Rectangle drawRect = new Rectangle(0, start * rh,
4485                                         getColumnModel().getTotalColumnWidth(),
4486                                            (getRowCount()-start) * rh);
4487 
4488         revalidate();
4489         // PENDING(milne) revalidate calls repaint() if parent is a ScrollPane
4490         // repaint still required in the unusual case where there is no ScrollPane
4491         repaint(drawRect);
4492     }
4493 
4494     /*
4495      * Invoked when rows have been removed from the table.
4496      * <p>
4497      * Application code will not use these methods explicitly, they
4498      * are used internally by JTable.
4499      *
4500      * @param e the TableModelEvent encapsulating the deletion
4501      */
4502     private void tableRowsDeleted(TableModelEvent e) {
4503         int start = e.getFirstRow();
4504         int end = e.getLastRow();
4505         if (start < 0) {
4506             start = 0;
4507         }
4508         if (end < 0) {
4509             end = getRowCount()-1;
4510         }
4511 
4512         int deletedCount = end - start + 1;
4513         int previousRowCount = getRowCount() + deletedCount;
4514         // Adjust the selection to account for the new rows
4515         selectionModel.removeIndexInterval(start, end);
4516 
4517         // If we have variable height rows, adjust the row model.
4518         if (rowModel != null) {
4519             rowModel.removeEntries(start, deletedCount);
4520         }
4521 
4522         int rh = getRowHeight();
4523         Rectangle drawRect = new Rectangle(0, start * rh,
4524                                         getColumnModel().getTotalColumnWidth(),
4525                                         (previousRowCount - start) * rh);
4526 
4527         revalidate();
4528         // PENDING(milne) revalidate calls repaint() if parent is a ScrollPane
4529         // repaint still required in the unusual case where there is no ScrollPane
4530         repaint(drawRect);
4531     }
4532 
4533 //
4534 // Implementing TableColumnModelListener interface
4535 //
4536 
4537     /**
4538      * Invoked when a column is added to the table column model.
4539      * <p>
4540      * Application code will not use these methods explicitly, they
4541      * are used internally by JTable.
4542      *
4543      * @see TableColumnModelListener
4544      */
4545     public void columnAdded(TableColumnModelEvent e) {
4546         // If I'm currently editing, then I should stop editing
4547         if (isEditing()) {
4548             removeEditor();
4549         }
4550         resizeAndRepaint();
4551     }
4552 
4553     /**
4554      * Invoked when a column is removed from the table column model.
4555      * <p>
4556      * Application code will not use these methods explicitly, they
4557      * are used internally by JTable.
4558      *
4559      * @see TableColumnModelListener
4560      */
4561     public void columnRemoved(TableColumnModelEvent e) {
4562         // If I'm currently editing, then I should stop editing
4563         if (isEditing()) {
4564             removeEditor();
4565         }
4566         resizeAndRepaint();
4567     }
4568 
4569     /**
4570      * Invoked when a column is repositioned. If a cell is being
4571      * edited, then editing is stopped and the cell is redrawn.
4572      * <p>
4573      * Application code will not use these methods explicitly, they
4574      * are used internally by JTable.
4575      *
4576      * @param e   the event received
4577      * @see TableColumnModelListener
4578      */
4579     public void columnMoved(TableColumnModelEvent e) {
4580         if (isEditing() && !getCellEditor().stopCellEditing()) {
4581             getCellEditor().cancelCellEditing();
4582         }
4583         repaint();
4584     }
4585 
4586     /**
4587      * Invoked when a column is moved due to a margin change.
4588      * If a cell is being edited, then editing is stopped and the cell
4589      * is redrawn.
4590      * <p>
4591      * Application code will not use these methods explicitly, they
4592      * are used internally by JTable.
4593      *
4594      * @param  e    the event received
4595      * @see TableColumnModelListener
4596      */
4597     public void columnMarginChanged(ChangeEvent e) {
4598         if (isEditing() && !getCellEditor().stopCellEditing()) {
4599             getCellEditor().cancelCellEditing();
4600         }
4601         TableColumn resizingColumn = getResizingColumn();
4602         // Need to do this here, before the parent's
4603         // layout manager calls getPreferredSize().
4604         if (resizingColumn != null && autoResizeMode == AUTO_RESIZE_OFF) {
4605             resizingColumn.setPreferredWidth(resizingColumn.getWidth());
4606         }
4607         resizeAndRepaint();
4608     }
4609 
4610     private int limit(int i, int a, int b) {
4611         return Math.min(b, Math.max(i, a));
4612     }
4613 
4614     /**
4615      * Invoked when the selection model of the <code>TableColumnModel</code>
4616      * is changed.
4617      * <p>
4618      * Application code will not use these methods explicitly, they
4619      * are used internally by JTable.
4620      *
4621      * @param  e  the event received
4622      * @see TableColumnModelListener
4623      */
4624     public void columnSelectionChanged(ListSelectionEvent e) {
4625         boolean isAdjusting = e.getValueIsAdjusting();
4626         if (columnSelectionAdjusting && !isAdjusting) {
4627             // The assumption is that when the model is no longer adjusting
4628             // we will have already gotten all the changes, and therefore
4629             // don't need to do an additional paint.
4630             columnSelectionAdjusting = false;
4631             return;
4632         }
4633         columnSelectionAdjusting = isAdjusting;
4634         // The getCellRect() call will fail unless there is at least one row.
4635         if (getRowCount() <= 0 || getColumnCount() <= 0) {
4636             return;
4637         }
4638         int firstIndex = limit(e.getFirstIndex(), 0, getColumnCount()-1);
4639         int lastIndex = limit(e.getLastIndex(), 0, getColumnCount()-1);
4640         int minRow = 0;
4641         int maxRow = getRowCount() - 1;
4642         if (getRowSelectionAllowed()) {
4643             minRow = selectionModel.getMinSelectionIndex();
4644             maxRow = selectionModel.getMaxSelectionIndex();
4645             int leadRow = getAdjustedIndex(selectionModel.getLeadSelectionIndex(), true);
4646 
4647             if (minRow == -1 || maxRow == -1) {
4648                 if (leadRow == -1) {
4649                     // nothing to repaint, return
4650                     return;
4651                 }
4652 
4653                 // only thing to repaint is the lead
4654                 minRow = maxRow = leadRow;
4655             } else {
4656                 // We need to consider more than just the range between
4657                 // the min and max selected index. The lead row, which could
4658                 // be outside this range, should be considered also.
4659                 if (leadRow != -1) {
4660                     minRow = Math.min(minRow, leadRow);
4661                     maxRow = Math.max(maxRow, leadRow);
4662                 }
4663             }
4664         }
4665         Rectangle firstColumnRect = getCellRect(minRow, firstIndex, false);
4666         Rectangle lastColumnRect = getCellRect(maxRow, lastIndex, false);
4667         Rectangle dirtyRegion = firstColumnRect.union(lastColumnRect);
4668         repaint(dirtyRegion);
4669     }
4670 
4671 //
4672 // Implementing ListSelectionListener interface
4673 //
4674 
4675     /**
4676      * Invoked when the row selection changes -- repaints to show the new
4677      * selection.
4678      * <p>
4679      * Application code will not use these methods explicitly, they
4680      * are used internally by JTable.
4681      *
4682      * @param e   the event received
4683      * @see ListSelectionListener
4684      */
4685     public void valueChanged(ListSelectionEvent e) {
4686         if (sortManager != null) {
4687             sortManager.viewSelectionChanged(e);
4688         }
4689         boolean isAdjusting = e.getValueIsAdjusting();
4690         if (rowSelectionAdjusting && !isAdjusting) {
4691             // The assumption is that when the model is no longer adjusting
4692             // we will have already gotten all the changes, and therefore
4693             // don't need to do an additional paint.
4694             rowSelectionAdjusting = false;
4695             return;
4696         }
4697         rowSelectionAdjusting = isAdjusting;
4698         // The getCellRect() calls will fail unless there is at least one column.
4699         if (getRowCount() <= 0 || getColumnCount() <= 0) {
4700             return;
4701         }
4702         int firstIndex = limit(e.getFirstIndex(), 0, getRowCount()-1);
4703         int lastIndex = limit(e.getLastIndex(), 0, getRowCount()-1);
4704         Rectangle firstRowRect = getCellRect(firstIndex, 0, false);
4705         Rectangle lastRowRect = getCellRect(lastIndex, getColumnCount()-1, false);
4706         Rectangle dirtyRegion = firstRowRect.union(lastRowRect);
4707         repaint(dirtyRegion);
4708     }
4709 
4710 //
4711 // Implementing the CellEditorListener interface
4712 //
4713 
4714     /**
4715      * Invoked when editing is finished. The changes are saved and the
4716      * editor is discarded.
4717      * <p>
4718      * Application code will not use these methods explicitly, they
4719      * are used internally by JTable.
4720      *
4721      * @param  e  the event received
4722      * @see CellEditorListener
4723      */
4724     public void editingStopped(ChangeEvent e) {
4725         // Take in the new value
4726         TableCellEditor editor = getCellEditor();
4727         if (editor != null) {
4728             Object value = editor.getCellEditorValue();
4729             setValueAt(value, editingRow, editingColumn);
4730             removeEditor();
4731         }
4732     }
4733 
4734     /**
4735      * Invoked when editing is canceled. The editor object is discarded
4736      * and the cell is rendered once again.
4737      * <p>
4738      * Application code will not use these methods explicitly, they
4739      * are used internally by JTable.
4740      *
4741      * @param  e  the event received
4742      * @see CellEditorListener
4743      */
4744     public void editingCanceled(ChangeEvent e) {
4745         removeEditor();
4746     }
4747 
4748 //
4749 // Implementing the Scrollable interface
4750 //
4751 
4752     /**
4753      * Sets the preferred size of the viewport for this table.
4754      *
4755      * @param size  a <code>Dimension</code> object specifying the <code>preferredSize</code> of a
4756      *              <code>JViewport</code> whose view is this table
4757      * @see Scrollable#getPreferredScrollableViewportSize
4758      * @beaninfo
4759      * description: The preferred size of the viewport.
4760      */
4761     public void setPreferredScrollableViewportSize(Dimension size) {
4762         preferredViewportSize = size;
4763     }
4764 
4765     /**
4766      * Returns the preferred size of the viewport for this table.
4767      *
4768      * @return a <code>Dimension</code> object containing the <code>preferredSize</code> of the <code>JViewport</code>
4769      *         which displays this table
4770      * @see Scrollable#getPreferredScrollableViewportSize
4771      */
4772     public Dimension getPreferredScrollableViewportSize() {
4773         return preferredViewportSize;
4774     }
4775 
4776     /**
4777      * Returns the scroll increment (in pixels) that completely exposes one new
4778      * row or column (depending on the orientation).
4779      * <p>
4780      * This method is called each time the user requests a unit scroll.
4781      *
4782      * @param visibleRect the view area visible within the viewport
4783      * @param orientation either <code>SwingConstants.VERTICAL</code>
4784      *                  or <code>SwingConstants.HORIZONTAL</code>
4785      * @param direction less than zero to scroll up/left,
4786      *                  greater than zero for down/right
4787      * @return the "unit" increment for scrolling in the specified direction
4788      * @see Scrollable#getScrollableUnitIncrement
4789      */
4790     public int getScrollableUnitIncrement(Rectangle visibleRect,
4791                                           int orientation,
4792                                           int direction) {
4793         int leadingRow;
4794         int leadingCol;
4795         Rectangle leadingCellRect;
4796 
4797         int leadingVisibleEdge;
4798         int leadingCellEdge;
4799         int leadingCellSize;
4800 
4801         leadingRow = getLeadingRow(visibleRect);
4802         leadingCol = getLeadingCol(visibleRect);
4803         if (orientation == SwingConstants.VERTICAL && leadingRow < 0) {
4804             // Couldn't find leading row - return some default value
4805             return getRowHeight();
4806         }
4807         else if (orientation == SwingConstants.HORIZONTAL && leadingCol < 0) {
4808             // Couldn't find leading col - return some default value
4809             return 100;
4810         }
4811 
4812         // Note that it's possible for one of leadingCol or leadingRow to be
4813         // -1, depending on the orientation.  This is okay, as getCellRect()
4814         // still provides enough information to calculate the unit increment.
4815         leadingCellRect = getCellRect(leadingRow, leadingCol, true);
4816         leadingVisibleEdge = leadingEdge(visibleRect, orientation);
4817         leadingCellEdge = leadingEdge(leadingCellRect, orientation);
4818 
4819         if (orientation == SwingConstants.VERTICAL) {
4820             leadingCellSize = leadingCellRect.height;
4821 
4822         }
4823         else {
4824             leadingCellSize = leadingCellRect.width;
4825         }
4826 
4827         // 4 cases:
4828         // #1: Leading cell fully visible, reveal next cell
4829         // #2: Leading cell fully visible, hide leading cell
4830         // #3: Leading cell partially visible, hide rest of leading cell
4831         // #4: Leading cell partially visible, reveal rest of leading cell
4832 
4833         if (leadingVisibleEdge == leadingCellEdge) { // Leading cell is fully
4834                                                      // visible
4835             // Case #1: Reveal previous cell
4836             if (direction < 0) {
4837                 int retVal = 0;
4838 
4839                 if (orientation == SwingConstants.VERTICAL) {
4840                     // Loop past any zero-height rows
4841                     while (--leadingRow >= 0) {
4842                         retVal = getRowHeight(leadingRow);
4843                         if (retVal != 0) {
4844                             break;
4845                         }
4846                     }
4847                 }
4848                 else { // HORIZONTAL
4849                     // Loop past any zero-width cols
4850                     while (--leadingCol >= 0) {
4851                         retVal = getCellRect(leadingRow, leadingCol, true).width;
4852                         if (retVal != 0) {
4853                             break;
4854                         }
4855                     }
4856                 }
4857                 return retVal;
4858             }
4859             else { // Case #2: hide leading cell
4860                 return leadingCellSize;
4861             }
4862         }
4863         else { // Leading cell is partially hidden
4864             // Compute visible, hidden portions
4865             int hiddenAmt = Math.abs(leadingVisibleEdge - leadingCellEdge);
4866             int visibleAmt = leadingCellSize - hiddenAmt;
4867 
4868             if (direction > 0) {
4869                 // Case #3: hide showing portion of leading cell
4870                 return visibleAmt;
4871             }
4872             else { // Case #4: reveal hidden portion of leading cell
4873                 return hiddenAmt;
4874             }
4875         }
4876     }
4877 
4878     /**
4879      * Returns <code>visibleRect.height</code> or
4880      * <code>visibleRect.width</code>,
4881      * depending on this table's orientation.  Note that as of Swing 1.1.1
4882      * (Java 2 v 1.2.2) the value
4883      * returned will ensure that the viewport is cleanly aligned on
4884      * a row boundary.
4885      *
4886      * @return <code>visibleRect.height</code> or
4887      *                                  <code>visibleRect.width</code>
4888      *                                  per the orientation
4889      * @see Scrollable#getScrollableBlockIncrement
4890      */
4891     public int getScrollableBlockIncrement(Rectangle visibleRect,
4892             int orientation, int direction) {
4893 
4894         if (getRowCount() == 0) {
4895             // Short-circuit empty table model
4896             if (SwingConstants.VERTICAL == orientation) {
4897                 int rh = getRowHeight();
4898                 return (rh > 0) ? Math.max(rh, (visibleRect.height / rh) * rh) :
4899                                   visibleRect.height;
4900             }
4901             else {
4902                 return visibleRect.width;
4903             }
4904         }
4905         // Shortcut for vertical scrolling of a table w/ uniform row height
4906         if (null == rowModel && SwingConstants.VERTICAL == orientation) {
4907             int row = rowAtPoint(visibleRect.getLocation());
4908             assert row != -1;
4909             int col = columnAtPoint(visibleRect.getLocation());
4910             Rectangle cellRect = getCellRect(row, col, true);
4911 
4912             if (cellRect.y == visibleRect.y) {
4913                 int rh = getRowHeight();
4914                 assert rh > 0;
4915                 return Math.max(rh, (visibleRect.height / rh) * rh);
4916             }
4917         }
4918         if (direction < 0) {
4919             return getPreviousBlockIncrement(visibleRect, orientation);
4920         }
4921         else {
4922             return getNextBlockIncrement(visibleRect, orientation);
4923         }
4924     }
4925 
4926     /**
4927      * Called to get the block increment for upward scrolling in cases of
4928      * horizontal scrolling, or for vertical scrolling of a table with
4929      * variable row heights.
4930      */
4931     private int getPreviousBlockIncrement(Rectangle visibleRect,
4932                                           int orientation) {
4933         // Measure back from visible leading edge
4934         // If we hit the cell on its leading edge, it becomes the leading cell.
4935         // Else, use following cell
4936 
4937         int row;
4938         int col;
4939 
4940         int   newEdge;
4941         Point newCellLoc;
4942 
4943         int visibleLeadingEdge = leadingEdge(visibleRect, orientation);
4944         boolean leftToRight = getComponentOrientation().isLeftToRight();
4945         int newLeadingEdge;
4946 
4947         // Roughly determine the new leading edge by measuring back from the
4948         // leading visible edge by the size of the visible rect, and find the
4949         // cell there.
4950         if (orientation == SwingConstants.VERTICAL) {
4951             newEdge = visibleLeadingEdge - visibleRect.height;
4952             int x = visibleRect.x + (leftToRight ? 0 : visibleRect.width);
4953             newCellLoc = new Point(x, newEdge);
4954         }
4955         else if (leftToRight) {
4956             newEdge = visibleLeadingEdge - visibleRect.width;
4957             newCellLoc = new Point(newEdge, visibleRect.y);
4958         }
4959         else { // Horizontal, right-to-left
4960             newEdge = visibleLeadingEdge + visibleRect.width;
4961             newCellLoc = new Point(newEdge - 1, visibleRect.y);
4962         }
4963         row = rowAtPoint(newCellLoc);
4964         col = columnAtPoint(newCellLoc);
4965 
4966         // If we're measuring past the beginning of the table, we get an invalid
4967         // cell.  Just go to the beginning of the table in this case.
4968         if (orientation == SwingConstants.VERTICAL & row < 0) {
4969             newLeadingEdge = 0;
4970         }
4971         else if (orientation == SwingConstants.HORIZONTAL & col < 0) {
4972             if (leftToRight) {
4973                 newLeadingEdge = 0;
4974             }
4975             else {
4976                 newLeadingEdge = getWidth();
4977             }
4978         }
4979         else {
4980             // Refine our measurement
4981             Rectangle newCellRect = getCellRect(row, col, true);
4982             int newCellLeadingEdge = leadingEdge(newCellRect, orientation);
4983             int newCellTrailingEdge = trailingEdge(newCellRect, orientation);
4984 
4985             // Usually, we hit in the middle of newCell, and want to scroll to
4986             // the beginning of the cell after newCell.  But there are a
4987             // couple corner cases where we want to scroll to the beginning of
4988             // newCell itself.  These cases are:
4989             // 1) newCell is so large that it ends at or extends into the
4990             //    visibleRect (newCell is the leading cell, or is adjacent to
4991             //    the leading cell)
4992             // 2) newEdge happens to fall right on the beginning of a cell
4993 
4994             // Case 1
4995             if ((orientation == SwingConstants.VERTICAL || leftToRight) &&
4996                 (newCellTrailingEdge >= visibleLeadingEdge)) {
4997                 newLeadingEdge = newCellLeadingEdge;
4998             }
4999             else if (orientation == SwingConstants.HORIZONTAL &&
5000                      !leftToRight &&
5001                      newCellTrailingEdge <= visibleLeadingEdge) {
5002                 newLeadingEdge = newCellLeadingEdge;
5003             }
5004             // Case 2:
5005             else if (newEdge == newCellLeadingEdge) {
5006                 newLeadingEdge = newCellLeadingEdge;
5007             }
5008             // Common case: scroll to cell after newCell
5009             else {
5010                 newLeadingEdge = newCellTrailingEdge;
5011             }
5012         }
5013         return Math.abs(visibleLeadingEdge - newLeadingEdge);
5014     }
5015 
5016     /**
5017      * Called to get the block increment for downward scrolling in cases of
5018      * horizontal scrolling, or for vertical scrolling of a table with
5019      * variable row heights.
5020      */
5021     private int getNextBlockIncrement(Rectangle visibleRect,
5022                                       int orientation) {
5023         // Find the cell at the trailing edge.  Return the distance to put
5024         // that cell at the leading edge.
5025         int trailingRow = getTrailingRow(visibleRect);
5026         int trailingCol = getTrailingCol(visibleRect);
5027 
5028         Rectangle cellRect;
5029         boolean cellFillsVis;
5030 
5031         int cellLeadingEdge;
5032         int cellTrailingEdge;
5033         int newLeadingEdge;
5034         int visibleLeadingEdge = leadingEdge(visibleRect, orientation);
5035 
5036         // If we couldn't find trailing cell, just return the size of the
5037         // visibleRect.  Note that, for instance, we don't need the
5038         // trailingCol to proceed if we're scrolling vertically, because
5039         // cellRect will still fill in the required dimensions.  This would
5040         // happen if we're scrolling vertically, and the table is not wide
5041         // enough to fill the visibleRect.
5042         if (orientation == SwingConstants.VERTICAL && trailingRow < 0) {
5043             return visibleRect.height;
5044         }
5045         else if (orientation == SwingConstants.HORIZONTAL && trailingCol < 0) {
5046             return visibleRect.width;
5047         }
5048         cellRect = getCellRect(trailingRow, trailingCol, true);
5049         cellLeadingEdge = leadingEdge(cellRect, orientation);
5050         cellTrailingEdge = trailingEdge(cellRect, orientation);
5051 
5052         if (orientation == SwingConstants.VERTICAL ||
5053             getComponentOrientation().isLeftToRight()) {
5054             cellFillsVis = cellLeadingEdge <= visibleLeadingEdge;
5055         }
5056         else { // Horizontal, right-to-left
5057             cellFillsVis = cellLeadingEdge >= visibleLeadingEdge;
5058         }
5059 
5060         if (cellFillsVis) {
5061             // The visibleRect contains a single large cell.  Scroll to the end
5062             // of this cell, so the following cell is the first cell.
5063             newLeadingEdge = cellTrailingEdge;
5064         }
5065         else if (cellTrailingEdge == trailingEdge(visibleRect, orientation)) {
5066             // The trailing cell happens to end right at the end of the
5067             // visibleRect.  Again, scroll to the beginning of the next cell.
5068             newLeadingEdge = cellTrailingEdge;
5069         }
5070         else {
5071             // Common case: the trailing cell is partially visible, and isn't
5072             // big enough to take up the entire visibleRect.  Scroll so it
5073             // becomes the leading cell.
5074             newLeadingEdge = cellLeadingEdge;
5075         }
5076         return Math.abs(newLeadingEdge - visibleLeadingEdge);
5077     }
5078 
5079     /*
5080      * Return the row at the top of the visibleRect
5081      *
5082      * May return -1
5083      */
5084     private int getLeadingRow(Rectangle visibleRect) {
5085         Point leadingPoint;
5086 
5087         if (getComponentOrientation().isLeftToRight()) {
5088             leadingPoint = new Point(visibleRect.x, visibleRect.y);
5089         }
5090         else {
5091             leadingPoint = new Point(visibleRect.x + visibleRect.width - 1,
5092                                      visibleRect.y);
5093         }
5094         return rowAtPoint(leadingPoint);
5095     }
5096 
5097     /*
5098      * Return the column at the leading edge of the visibleRect.
5099      *
5100      * May return -1
5101      */
5102     private int getLeadingCol(Rectangle visibleRect) {
5103         Point leadingPoint;
5104 
5105         if (getComponentOrientation().isLeftToRight()) {
5106             leadingPoint = new Point(visibleRect.x, visibleRect.y);
5107         }
5108         else {
5109             leadingPoint = new Point(visibleRect.x + visibleRect.width - 1,
5110                                      visibleRect.y);
5111         }
5112         return columnAtPoint(leadingPoint);
5113     }
5114 
5115     /*
5116      * Return the row at the bottom of the visibleRect.
5117      *
5118      * May return -1
5119      */
5120     private int getTrailingRow(Rectangle visibleRect) {
5121         Point trailingPoint;
5122 
5123         if (getComponentOrientation().isLeftToRight()) {
5124             trailingPoint = new Point(visibleRect.x,
5125                                       visibleRect.y + visibleRect.height - 1);
5126         }
5127         else {
5128             trailingPoint = new Point(visibleRect.x + visibleRect.width - 1,
5129                                       visibleRect.y + visibleRect.height - 1);
5130         }
5131         return rowAtPoint(trailingPoint);
5132     }
5133 
5134     /*
5135      * Return the column at the trailing edge of the visibleRect.
5136      *
5137      * May return -1
5138      */
5139     private int getTrailingCol(Rectangle visibleRect) {
5140         Point trailingPoint;
5141 
5142         if (getComponentOrientation().isLeftToRight()) {
5143             trailingPoint = new Point(visibleRect.x + visibleRect.width - 1,
5144                                       visibleRect.y);
5145         }
5146         else {
5147             trailingPoint = new Point(visibleRect.x, visibleRect.y);
5148         }
5149         return columnAtPoint(trailingPoint);
5150     }
5151 
5152     /*
5153      * Returns the leading edge ("beginning") of the given Rectangle.
5154      * For VERTICAL, this is the top, for left-to-right, the left side, and for
5155      * right-to-left, the right side.
5156      */
5157     private int leadingEdge(Rectangle rect, int orientation) {
5158         if (orientation == SwingConstants.VERTICAL) {
5159             return rect.y;
5160         }
5161         else if (getComponentOrientation().isLeftToRight()) {
5162             return rect.x;
5163         }
5164         else { // Horizontal, right-to-left
5165             return rect.x + rect.width;
5166         }
5167     }
5168 
5169     /*
5170      * Returns the trailing edge ("end") of the given Rectangle.
5171      * For VERTICAL, this is the bottom, for left-to-right, the right side, and
5172      * for right-to-left, the left side.
5173      */
5174     private int trailingEdge(Rectangle rect, int orientation) {
5175         if (orientation == SwingConstants.VERTICAL) {
5176             return rect.y + rect.height;
5177         }
5178         else if (getComponentOrientation().isLeftToRight()) {
5179             return rect.x + rect.width;
5180         }
5181         else { // Horizontal, right-to-left
5182             return rect.x;
5183         }
5184     }
5185 
5186     /**
5187      * Returns false if <code>autoResizeMode</code> is set to
5188      * <code>AUTO_RESIZE_OFF</code>, which indicates that the
5189      * width of the viewport does not determine the width
5190      * of the table.  Otherwise returns true.
5191      *
5192      * @return false if <code>autoResizeMode</code> is set
5193      *   to <code>AUTO_RESIZE_OFF</code>, otherwise returns true
5194      * @see Scrollable#getScrollableTracksViewportWidth
5195      */
5196     public boolean getScrollableTracksViewportWidth() {
5197         return !(autoResizeMode == AUTO_RESIZE_OFF);
5198     }
5199 
5200     /**
5201      * Returns {@code false} to indicate that the height of the viewport does
5202      * not determine the height of the table, unless
5203      * {@code getFillsViewportHeight} is {@code true} and the preferred height
5204      * of the table is smaller than the viewport's height.
5205      *
5206      * @return {@code false} unless {@code getFillsViewportHeight} is
5207      *         {@code true} and the table needs to be stretched to fill
5208      *         the viewport
5209      * @see Scrollable#getScrollableTracksViewportHeight
5210      * @see #setFillsViewportHeight
5211      * @see #getFillsViewportHeight
5212      */
5213     public boolean getScrollableTracksViewportHeight() {
5214         Container parent = SwingUtilities.getUnwrappedParent(this);
5215         return getFillsViewportHeight()
5216                && parent instanceof JViewport
5217                && parent.getHeight() > getPreferredSize().height;
5218     }
5219 
5220     /**
5221      * Sets whether or not this table is always made large enough
5222      * to fill the height of an enclosing viewport. If the preferred
5223      * height of the table is smaller than the viewport, then the table
5224      * will be stretched to fill the viewport. In other words, this
5225      * ensures the table is never smaller than the viewport.
5226      * The default for this property is {@code false}.
5227      *
5228      * @param fillsViewportHeight whether or not this table is always
5229      *        made large enough to fill the height of an enclosing
5230      *        viewport
5231      * @see #getFillsViewportHeight
5232      * @see #getScrollableTracksViewportHeight
5233      * @since 1.6
5234      * @beaninfo
5235      *      bound: true
5236      *      description: Whether or not this table is always made large enough
5237      *                   to fill the height of an enclosing viewport
5238      */
5239     public void setFillsViewportHeight(boolean fillsViewportHeight) {
5240         boolean old = this.fillsViewportHeight;
5241         this.fillsViewportHeight = fillsViewportHeight;
5242         resizeAndRepaint();
5243         firePropertyChange("fillsViewportHeight", old, fillsViewportHeight);
5244     }
5245 
5246     /**
5247      * Returns whether or not this table is always made large enough
5248      * to fill the height of an enclosing viewport.
5249      *
5250      * @return whether or not this table is always made large enough
5251      *         to fill the height of an enclosing viewport
5252      * @see #setFillsViewportHeight
5253      * @since 1.6
5254      */
5255     public boolean getFillsViewportHeight() {
5256         return fillsViewportHeight;
5257     }
5258 
5259 //
5260 // Protected Methods
5261 //
5262 
5263     protected boolean processKeyBinding(KeyStroke ks, KeyEvent e,
5264                                         int condition, boolean pressed) {
5265         boolean retValue = super.processKeyBinding(ks, e, condition, pressed);
5266 
5267         // Start editing when a key is typed. UI classes can disable this behavior
5268         // by setting the client property JTable.autoStartsEdit to Boolean.FALSE.
5269         if (!retValue && condition == WHEN_ANCESTOR_OF_FOCUSED_COMPONENT &&
5270             isFocusOwner() &&
5271             !Boolean.FALSE.equals(getClientProperty("JTable.autoStartsEdit"))) {
5272             // We do not have a binding for the event.
5273             Component editorComponent = getEditorComponent();
5274             if (editorComponent == null) {
5275                 // Only attempt to install the editor on a KEY_PRESSED,
5276                 if (e == null || e.getID() != KeyEvent.KEY_PRESSED) {
5277                     return false;
5278                 }
5279                 // Don't start when just a modifier is pressed
5280                 int code = e.getKeyCode();
5281                 if (code == KeyEvent.VK_SHIFT || code == KeyEvent.VK_CONTROL ||
5282                     code == KeyEvent.VK_ALT) {
5283                     return false;
5284                 }
5285                 // Try to install the editor
5286                 int leadRow = getSelectionModel().getLeadSelectionIndex();
5287                 int leadColumn = getColumnModel().getSelectionModel().
5288                                    getLeadSelectionIndex();
5289                 if (leadRow != -1 && leadColumn != -1 && !isEditing()) {
5290                     if (!editCellAt(leadRow, leadColumn, e)) {
5291                         return false;
5292                     }
5293                 }
5294                 editorComponent = getEditorComponent();
5295                 if (editorComponent == null) {
5296                     return false;
5297                 }
5298             }
5299             // If the editorComponent is a JComponent, pass the event to it.
5300             if (editorComponent instanceof JComponent) {
5301                 retValue = ((JComponent)editorComponent).processKeyBinding
5302                                         (ks, e, WHEN_FOCUSED, pressed);
5303                 // If we have started an editor as a result of the user
5304                 // pressing a key and the surrendersFocusOnKeystroke property
5305                 // is true, give the focus to the new editor.
5306                 if (getSurrendersFocusOnKeystroke()) {
5307                     editorComponent.requestFocus();
5308                 }
5309             }
5310         }
5311         return retValue;
5312     }
5313 
5314     /**
5315      * Creates default cell renderers for objects, numbers, doubles, dates,
5316      * booleans, and icons.
5317      * @see javax.swing.table.DefaultTableCellRenderer
5318      *
5319      */
5320     protected void createDefaultRenderers() {
5321         defaultRenderersByColumnClass = new UIDefaults(8, 0.75f);
5322 
5323         // Objects
5324         defaultRenderersByColumnClass.put(Object.class, (UIDefaults.LazyValue) t -> new DefaultTableCellRenderer.UIResource());
5325 
5326         // Numbers
5327         defaultRenderersByColumnClass.put(Number.class, (UIDefaults.LazyValue) t -> new NumberRenderer());
5328 
5329         // Doubles and Floats
5330         defaultRenderersByColumnClass.put(Float.class, (UIDefaults.LazyValue) t -> new DoubleRenderer());
5331         defaultRenderersByColumnClass.put(Double.class, (UIDefaults.LazyValue) t -> new DoubleRenderer());
5332 
5333         // Dates
5334         defaultRenderersByColumnClass.put(Date.class, (UIDefaults.LazyValue) t -> new DateRenderer());
5335 
5336         // Icons and ImageIcons
5337         defaultRenderersByColumnClass.put(Icon.class, (UIDefaults.LazyValue) t -> new IconRenderer());
5338         defaultRenderersByColumnClass.put(ImageIcon.class, (UIDefaults.LazyValue) t -> new IconRenderer());
5339 
5340         // Booleans
5341         defaultRenderersByColumnClass.put(Boolean.class, (UIDefaults.LazyValue) t -> new BooleanRenderer());
5342     }
5343 
5344     /**
5345      * Default Renderers
5346      **/
5347     static class NumberRenderer extends DefaultTableCellRenderer.UIResource {
5348         public NumberRenderer() {
5349             super();
5350             setHorizontalAlignment(JLabel.RIGHT);
5351         }
5352     }
5353 
5354     static class DoubleRenderer extends NumberRenderer {
5355         NumberFormat formatter;
5356         public DoubleRenderer() { super(); }
5357 
5358         public void setValue(Object value) {
5359             if (formatter == null) {
5360                 formatter = NumberFormat.getInstance();
5361             }
5362             setText((value == null) ? "" : formatter.format(value));
5363         }
5364     }
5365 
5366     static class DateRenderer extends DefaultTableCellRenderer.UIResource {
5367         DateFormat formatter;
5368         public DateRenderer() { super(); }
5369 
5370         public void setValue(Object value) {
5371             if (formatter==null) {
5372                 formatter = DateFormat.getDateInstance();
5373             }
5374             setText((value == null) ? "" : formatter.format(value));
5375         }
5376     }
5377 
5378     static class IconRenderer extends DefaultTableCellRenderer.UIResource {
5379         public IconRenderer() {
5380             super();
5381             setHorizontalAlignment(JLabel.CENTER);
5382         }
5383         public void setValue(Object value) { setIcon((value instanceof Icon) ? (Icon)value : null); }
5384     }
5385 
5386 
5387     static class BooleanRenderer extends JCheckBox implements TableCellRenderer, UIResource
5388     {
5389         private static final Border noFocusBorder = new EmptyBorder(1, 1, 1, 1);
5390 
5391         public BooleanRenderer() {
5392             super();
5393             setHorizontalAlignment(JLabel.CENTER);
5394             setBorderPainted(true);
5395         }
5396 
5397         public Component getTableCellRendererComponent(JTable table, Object value,
5398                                                        boolean isSelected, boolean hasFocus, int row, int column) {
5399             if (isSelected) {
5400                 setForeground(table.getSelectionForeground());
5401                 super.setBackground(table.getSelectionBackground());
5402             }
5403             else {
5404                 setForeground(table.getForeground());
5405                 setBackground(table.getBackground());
5406             }
5407             setSelected((value != null && ((Boolean)value).booleanValue()));
5408 
5409             if (hasFocus) {
5410                 setBorder(UIManager.getBorder("Table.focusCellHighlightBorder"));
5411             } else {
5412                 setBorder(noFocusBorder);
5413             }
5414 
5415             return this;
5416         }
5417     }
5418 
5419     /**
5420      * Creates default cell editors for objects, numbers, and boolean values.
5421      * @see DefaultCellEditor
5422      */
5423     protected void createDefaultEditors() {
5424         defaultEditorsByColumnClass = new UIDefaults(3, 0.75f);
5425 
5426         // Objects
5427         defaultEditorsByColumnClass.put(Object.class, (UIDefaults.LazyValue) t -> new GenericEditor());
5428 
5429         // Numbers
5430         defaultEditorsByColumnClass.put(Number.class, (UIDefaults.LazyValue) t -> new NumberEditor());
5431 
5432         // Booleans
5433         defaultEditorsByColumnClass.put(Boolean.class, (UIDefaults.LazyValue) t -> new BooleanEditor());
5434     }
5435 
5436     /**
5437      * Default Editors
5438      */
5439     static class GenericEditor extends DefaultCellEditor {
5440 
5441         Class[] argTypes = new Class[]{String.class};
5442         java.lang.reflect.Constructor constructor;
5443         Object value;
5444 
5445         public GenericEditor() {
5446             super(new JTextField());
5447             getComponent().setName("Table.editor");
5448         }
5449 
5450         public boolean stopCellEditing() {
5451             String s = (String)super.getCellEditorValue();
5452             // Here we are dealing with the case where a user
5453             // has deleted the string value in a cell, possibly
5454             // after a failed validation. Return null, so that
5455             // they have the option to replace the value with
5456             // null or use escape to restore the original.
5457             // For Strings, return "" for backward compatibility.
5458             try {
5459                 if ("".equals(s)) {
5460                     if (constructor.getDeclaringClass() == String.class) {
5461                         value = s;
5462                     }
5463                     return super.stopCellEditing();
5464                 }
5465 
5466                 SwingUtilities2.checkAccess(constructor.getModifiers());
5467                 value = constructor.newInstance(new Object[]{s});
5468             }
5469             catch (Exception e) {
5470                 ((JComponent)getComponent()).setBorder(new LineBorder(Color.red));
5471                 return false;
5472             }
5473             return super.stopCellEditing();
5474         }
5475 
5476         public Component getTableCellEditorComponent(JTable table, Object value,
5477                                                  boolean isSelected,
5478                                                  int row, int column) {
5479             this.value = null;
5480             ((JComponent)getComponent()).setBorder(new LineBorder(Color.black));
5481             try {
5482                 Class<?> type = table.getColumnClass(column);
5483                 // Since our obligation is to produce a value which is
5484                 // assignable for the required type it is OK to use the
5485                 // String constructor for columns which are declared
5486                 // to contain Objects. A String is an Object.
5487                 if (type == Object.class) {
5488                     type = String.class;
5489                 }
5490                 ReflectUtil.checkPackageAccess(type);
5491                 SwingUtilities2.checkAccess(type.getModifiers());
5492                 constructor = type.getConstructor(argTypes);
5493             }
5494             catch (Exception e) {
5495                 return null;
5496             }
5497             return super.getTableCellEditorComponent(table, value, isSelected, row, column);
5498         }
5499 
5500         public Object getCellEditorValue() {
5501             return value;
5502         }
5503     }
5504 
5505     static class NumberEditor extends GenericEditor {
5506 
5507         public NumberEditor() {
5508             ((JTextField)getComponent()).setHorizontalAlignment(JTextField.RIGHT);
5509         }
5510     }
5511 
5512     static class BooleanEditor extends DefaultCellEditor {
5513         public BooleanEditor() {
5514             super(new JCheckBox());
5515             JCheckBox checkBox = (JCheckBox)getComponent();
5516             checkBox.setHorizontalAlignment(JCheckBox.CENTER);
5517         }
5518     }
5519 
5520     /**
5521      * Initializes table properties to their default values.
5522      */
5523     protected void initializeLocalVars() {
5524         updateSelectionOnSort = true;
5525         setOpaque(true);
5526         createDefaultRenderers();
5527         createDefaultEditors();
5528 
5529         setTableHeader(createDefaultTableHeader());
5530 
5531         setShowGrid(true);
5532         setAutoResizeMode(AUTO_RESIZE_SUBSEQUENT_COLUMNS);
5533         setRowHeight(16);
5534         isRowHeightSet = false;
5535         setRowMargin(1);
5536         setRowSelectionAllowed(true);
5537         setCellEditor(null);
5538         setEditingColumn(-1);
5539         setEditingRow(-1);
5540         setSurrendersFocusOnKeystroke(false);
5541         setPreferredScrollableViewportSize(new Dimension(450, 400));
5542 
5543         // I'm registered to do tool tips so we can draw tips for the renderers
5544         ToolTipManager toolTipManager = ToolTipManager.sharedInstance();
5545         toolTipManager.registerComponent(this);
5546 
5547         setAutoscrolls(true);
5548     }
5549 
5550     /**
5551      * Returns the default table model object, which is
5552      * a <code>DefaultTableModel</code>.  A subclass can override this
5553      * method to return a different table model object.
5554      *
5555      * @return the default table model object
5556      * @see javax.swing.table.DefaultTableModel
5557      */
5558     protected TableModel createDefaultDataModel() {
5559         return new DefaultTableModel();
5560     }
5561 
5562     /**
5563      * Returns the default column model object, which is
5564      * a <code>DefaultTableColumnModel</code>.  A subclass can override this
5565      * method to return a different column model object.
5566      *
5567      * @return the default column model object
5568      * @see javax.swing.table.DefaultTableColumnModel
5569      */
5570     protected TableColumnModel createDefaultColumnModel() {
5571         return new DefaultTableColumnModel();
5572     }
5573 
5574     /**
5575      * Returns the default selection model object, which is
5576      * a <code>DefaultListSelectionModel</code>.  A subclass can override this
5577      * method to return a different selection model object.
5578      *
5579      * @return the default selection model object
5580      * @see javax.swing.DefaultListSelectionModel
5581      */
5582     protected ListSelectionModel createDefaultSelectionModel() {
5583         return new DefaultListSelectionModel();
5584     }
5585 
5586     /**
5587      * Returns the default table header object, which is
5588      * a <code>JTableHeader</code>.  A subclass can override this
5589      * method to return a different table header object.
5590      *
5591      * @return the default table header object
5592      * @see javax.swing.table.JTableHeader
5593      */
5594     protected JTableHeader createDefaultTableHeader() {
5595         return new JTableHeader(columnModel);
5596     }
5597 
5598     /**
5599      * Equivalent to <code>revalidate</code> followed by <code>repaint</code>.
5600      */
5601     protected void resizeAndRepaint() {
5602         revalidate();
5603         repaint();
5604     }
5605 
5606     /**
5607      * Returns the active cell editor, which is {@code null} if the table
5608      * is not currently editing.
5609      *
5610      * @return the {@code TableCellEditor} that does the editing,
5611      *         or {@code null} if the table is not currently editing.
5612      * @see #cellEditor
5613      * @see #getCellEditor(int, int)
5614      */
5615     public TableCellEditor getCellEditor() {
5616         return cellEditor;
5617     }
5618 
5619     /**
5620      * Sets the active cell editor.
5621      *
5622      * @param anEditor the active cell editor
5623      * @see #cellEditor
5624      * @beaninfo
5625      *  bound: true
5626      *  description: The table's active cell editor.
5627      */
5628     public void setCellEditor(TableCellEditor anEditor) {
5629         TableCellEditor oldEditor = cellEditor;
5630         cellEditor = anEditor;
5631         firePropertyChange("tableCellEditor", oldEditor, anEditor);
5632     }
5633 
5634     /**
5635      * Sets the <code>editingColumn</code> variable.
5636      * @param aColumn  the column of the cell to be edited
5637      *
5638      * @see #editingColumn
5639      */
5640     public void setEditingColumn(int aColumn) {
5641         editingColumn = aColumn;
5642     }
5643 
5644     /**
5645      * Sets the <code>editingRow</code> variable.
5646      * @param aRow  the row of the cell to be edited
5647      *
5648      * @see #editingRow
5649      */
5650     public void setEditingRow(int aRow) {
5651         editingRow = aRow;
5652     }
5653 
5654     /**
5655      * Returns an appropriate renderer for the cell specified by this row and
5656      * column. If the <code>TableColumn</code> for this column has a non-null
5657      * renderer, returns that.  If not, finds the class of the data in
5658      * this column (using <code>getColumnClass</code>)
5659      * and returns the default renderer for this type of data.
5660      * <p>
5661      * <b>Note:</b>
5662      * Throughout the table package, the internal implementations always
5663      * use this method to provide renderers so that this default behavior
5664      * can be safely overridden by a subclass.
5665      *
5666      * @param row       the row of the cell to render, where 0 is the first row
5667      * @param column    the column of the cell to render,
5668      *                  where 0 is the first column
5669      * @return the assigned renderer; if <code>null</code>
5670      *                  returns the default renderer
5671      *                  for this type of object
5672      * @see javax.swing.table.DefaultTableCellRenderer
5673      * @see javax.swing.table.TableColumn#setCellRenderer
5674      * @see #setDefaultRenderer
5675      */
5676     public TableCellRenderer getCellRenderer(int row, int column) {
5677         TableColumn tableColumn = getColumnModel().getColumn(column);
5678         TableCellRenderer renderer = tableColumn.getCellRenderer();
5679         if (renderer == null) {
5680             renderer = getDefaultRenderer(getColumnClass(column));
5681         }
5682         return renderer;
5683     }
5684 
5685     /**
5686      * Prepares the renderer by querying the data model for the
5687      * value and selection state
5688      * of the cell at <code>row</code>, <code>column</code>.
5689      * Returns the component (may be a <code>Component</code>
5690      * or a <code>JComponent</code>) under the event location.
5691      * <p>
5692      * During a printing operation, this method will configure the
5693      * renderer without indicating selection or focus, to prevent
5694      * them from appearing in the printed output. To do other
5695      * customizations based on whether or not the table is being
5696      * printed, you can check the value of
5697      * {@link javax.swing.JComponent#isPaintingForPrint()}, either here
5698      * or within custom renderers.
5699      * <p>
5700      * <b>Note:</b>
5701      * Throughout the table package, the internal implementations always
5702      * use this method to prepare renderers so that this default behavior
5703      * can be safely overridden by a subclass.
5704      *
5705      * @param renderer  the <code>TableCellRenderer</code> to prepare
5706      * @param row       the row of the cell to render, where 0 is the first row
5707      * @param column    the column of the cell to render,
5708      *                  where 0 is the first column
5709      * @return          the <code>Component</code> under the event location
5710      */
5711     public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
5712         Object value = getValueAt(row, column);
5713 
5714         boolean isSelected = false;
5715         boolean hasFocus = false;
5716 
5717         // Only indicate the selection and focused cell if not printing
5718         if (!isPaintingForPrint()) {
5719             isSelected = isCellSelected(row, column);
5720 
5721             boolean rowIsLead =
5722                 (selectionModel.getLeadSelectionIndex() == row);
5723             boolean colIsLead =
5724                 (columnModel.getSelectionModel().getLeadSelectionIndex() == column);
5725 
5726             hasFocus = (rowIsLead && colIsLead) && isFocusOwner();
5727         }
5728 
5729         return renderer.getTableCellRendererComponent(this, value,
5730                                                       isSelected, hasFocus,
5731                                                       row, column);
5732     }
5733 
5734     /**
5735      * Returns an appropriate editor for the cell specified by
5736      * <code>row</code> and <code>column</code>. If the
5737      * <code>TableColumn</code> for this column has a non-null editor,
5738      * returns that.  If not, finds the class of the data in this
5739      * column (using <code>getColumnClass</code>)
5740      * and returns the default editor for this type of data.
5741      * <p>
5742      * <b>Note:</b>
5743      * Throughout the table package, the internal implementations always
5744      * use this method to provide editors so that this default behavior
5745      * can be safely overridden by a subclass.
5746      *
5747      * @param row       the row of the cell to edit, where 0 is the first row
5748      * @param column    the column of the cell to edit,
5749      *                  where 0 is the first column
5750      * @return          the editor for this cell;
5751      *                  if <code>null</code> return the default editor for
5752      *                  this type of cell
5753      * @see DefaultCellEditor
5754      */
5755     public TableCellEditor getCellEditor(int row, int column) {
5756         TableColumn tableColumn = getColumnModel().getColumn(column);
5757         TableCellEditor editor = tableColumn.getCellEditor();
5758         if (editor == null) {
5759             editor = getDefaultEditor(getColumnClass(column));
5760         }
5761         return editor;
5762     }
5763 
5764 
5765     /**
5766      * Prepares the editor by querying the data model for the value and
5767      * selection state of the cell at <code>row</code>, <code>column</code>.
5768      * <p>
5769      * <b>Note:</b>
5770      * Throughout the table package, the internal implementations always
5771      * use this method to prepare editors so that this default behavior
5772      * can be safely overridden by a subclass.
5773      *
5774      * @param editor  the <code>TableCellEditor</code> to set up
5775      * @param row     the row of the cell to edit,
5776      *                where 0 is the first row
5777      * @param column  the column of the cell to edit,
5778      *                where 0 is the first column
5779      * @return the <code>Component</code> being edited
5780      */
5781     public Component prepareEditor(TableCellEditor editor, int row, int column) {
5782         Object value = getValueAt(row, column);
5783         boolean isSelected = isCellSelected(row, column);
5784         Component comp = editor.getTableCellEditorComponent(this, value, isSelected,
5785                                                   row, column);
5786         if (comp instanceof JComponent) {
5787             JComponent jComp = (JComponent)comp;
5788             if (jComp.getNextFocusableComponent() == null) {
5789                 jComp.setNextFocusableComponent(this);
5790             }
5791         }
5792         return comp;
5793     }
5794 
5795     /**
5796      * Discards the editor object and frees the real estate it used for
5797      * cell rendering.
5798      */
5799     public void removeEditor() {
5800         KeyboardFocusManager.getCurrentKeyboardFocusManager().
5801             removePropertyChangeListener("permanentFocusOwner", editorRemover);
5802         editorRemover = null;
5803 
5804         TableCellEditor editor = getCellEditor();
5805         if(editor != null) {
5806             editor.removeCellEditorListener(this);
5807             if (editorComp != null) {
5808                 Component focusOwner =
5809                         KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
5810                 boolean isFocusOwnerInTheTable = focusOwner != null?
5811                         SwingUtilities.isDescendingFrom(focusOwner, this):false;
5812                 remove(editorComp);
5813                 if(isFocusOwnerInTheTable) {
5814                     requestFocusInWindow();
5815                 }
5816             }
5817 
5818             Rectangle cellRect = getCellRect(editingRow, editingColumn, false);
5819 
5820             setCellEditor(null);
5821             setEditingColumn(-1);
5822             setEditingRow(-1);
5823             editorComp = null;
5824 
5825             repaint(cellRect);
5826         }
5827     }
5828 
5829 //
5830 // Serialization
5831 //
5832 
5833     /**
5834      * See readObject() and writeObject() in JComponent for more
5835      * information about serialization in Swing.
5836      */
5837     private void writeObject(ObjectOutputStream s) throws IOException {
5838         s.defaultWriteObject();
5839         if (getUIClassID().equals(uiClassID)) {
5840             byte count = JComponent.getWriteObjCounter(this);
5841             JComponent.setWriteObjCounter(this, --count);
5842             if (count == 0 && ui != null) {
5843                 ui.installUI(this);
5844             }
5845         }
5846     }
5847 
5848     private void readObject(ObjectInputStream s)
5849         throws IOException, ClassNotFoundException
5850     {
5851         s.defaultReadObject();
5852         if ((ui != null) && (getUIClassID().equals(uiClassID))) {
5853             ui.installUI(this);
5854         }
5855         createDefaultRenderers();
5856         createDefaultEditors();
5857 
5858         // If ToolTipText != null, then the tooltip has already been
5859         // registered by JComponent.readObject() and we don't want
5860         // to re-register here
5861         if (getToolTipText() == null) {
5862             ToolTipManager.sharedInstance().registerComponent(this);
5863          }
5864     }
5865 
5866     /* Called from the JComponent's EnableSerializationFocusListener to
5867      * do any Swing-specific pre-serialization configuration.
5868      */
5869     void compWriteObjectNotify() {
5870         super.compWriteObjectNotify();
5871         // If ToolTipText != null, then the tooltip has already been
5872         // unregistered by JComponent.compWriteObjectNotify()
5873         if (getToolTipText() == null) {
5874             ToolTipManager.sharedInstance().unregisterComponent(this);
5875         }
5876     }
5877 
5878     /**
5879      * Returns a string representation of this table. This method
5880      * is intended to be used only for debugging purposes, and the
5881      * content and format of the returned string may vary between
5882      * implementations. The returned string may be empty but may not
5883      * be <code>null</code>.
5884      *
5885      * @return  a string representation of this table
5886      */
5887     protected String paramString() {
5888         String gridColorString = (gridColor != null ?
5889                                   gridColor.toString() : "");
5890         String showHorizontalLinesString = (showHorizontalLines ?
5891                                             "true" : "false");
5892         String showVerticalLinesString = (showVerticalLines ?
5893                                           "true" : "false");
5894         String autoResizeModeString;
5895         if (autoResizeMode == AUTO_RESIZE_OFF) {
5896             autoResizeModeString = "AUTO_RESIZE_OFF";
5897         } else if (autoResizeMode == AUTO_RESIZE_NEXT_COLUMN) {
5898             autoResizeModeString = "AUTO_RESIZE_NEXT_COLUMN";
5899         } else if (autoResizeMode == AUTO_RESIZE_SUBSEQUENT_COLUMNS) {
5900             autoResizeModeString = "AUTO_RESIZE_SUBSEQUENT_COLUMNS";
5901         } else if (autoResizeMode == AUTO_RESIZE_LAST_COLUMN) {
5902             autoResizeModeString = "AUTO_RESIZE_LAST_COLUMN";
5903         } else if (autoResizeMode == AUTO_RESIZE_ALL_COLUMNS)  {
5904             autoResizeModeString = "AUTO_RESIZE_ALL_COLUMNS";
5905         } else autoResizeModeString = "";
5906         String autoCreateColumnsFromModelString = (autoCreateColumnsFromModel ?
5907                                                    "true" : "false");
5908         String preferredViewportSizeString = (preferredViewportSize != null ?
5909                                               preferredViewportSize.toString()
5910                                               : "");
5911         String rowSelectionAllowedString = (rowSelectionAllowed ?
5912                                             "true" : "false");
5913         String cellSelectionEnabledString = (cellSelectionEnabled ?
5914                                             "true" : "false");
5915         String selectionForegroundString = (selectionForeground != null ?
5916                                             selectionForeground.toString() :
5917                                             "");
5918         String selectionBackgroundString = (selectionBackground != null ?
5919                                             selectionBackground.toString() :
5920                                             "");
5921 
5922         return super.paramString() +
5923         ",autoCreateColumnsFromModel=" + autoCreateColumnsFromModelString +
5924         ",autoResizeMode=" + autoResizeModeString +
5925         ",cellSelectionEnabled=" + cellSelectionEnabledString +
5926         ",editingColumn=" + editingColumn +
5927         ",editingRow=" + editingRow +
5928         ",gridColor=" + gridColorString +
5929         ",preferredViewportSize=" + preferredViewportSizeString +
5930         ",rowHeight=" + rowHeight +
5931         ",rowMargin=" + rowMargin +
5932         ",rowSelectionAllowed=" + rowSelectionAllowedString +
5933         ",selectionBackground=" + selectionBackgroundString +
5934         ",selectionForeground=" + selectionForegroundString +
5935         ",showHorizontalLines=" + showHorizontalLinesString +
5936         ",showVerticalLines=" + showVerticalLinesString;
5937     }
5938 
5939     // This class tracks changes in the keyboard focus state. It is used
5940     // when the JTable is editing to determine when to cancel the edit.
5941     // If focus switches to a component outside of the jtable, but in the
5942     // same window, this will cancel editing.
5943     class CellEditorRemover implements PropertyChangeListener {
5944         KeyboardFocusManager focusManager;
5945 
5946         public CellEditorRemover(KeyboardFocusManager fm) {
5947             this.focusManager = fm;
5948         }
5949 
5950         public void propertyChange(PropertyChangeEvent ev) {
5951             if (!isEditing() || getClientProperty("terminateEditOnFocusLost") != Boolean.TRUE) {
5952                 return;
5953             }
5954 
5955             Component c = focusManager.getPermanentFocusOwner();
5956             while (c != null) {
5957                 if (c == JTable.this) {
5958                     // focus remains inside the table
5959                     return;
5960                 } else if ((c instanceof Window) ||
5961                            (c instanceof Applet && c.getParent() == null)) {
5962                     if (c == SwingUtilities.getRoot(JTable.this)) {
5963                         if (!getCellEditor().stopCellEditing()) {
5964                             getCellEditor().cancelCellEditing();
5965                         }
5966                     }
5967                     break;
5968                 }
5969                 c = c.getParent();
5970             }
5971         }
5972     }
5973 
5974 /////////////////
5975 // Printing Support
5976 /////////////////
5977 
5978     /**
5979      * A convenience method that displays a printing dialog, and then prints
5980      * this <code>JTable</code> in mode <code>PrintMode.FIT_WIDTH</code>,
5981      * with no header or footer text. A modal progress dialog, with an abort
5982      * option, will be shown for the duration of printing.
5983      * <p>
5984      * Note: In headless mode, no dialogs are shown and printing
5985      * occurs on the default printer.
5986      *
5987      * @return true, unless printing is cancelled by the user
5988      * @throws SecurityException if this thread is not allowed to
5989      *                           initiate a print job request
5990      * @throws PrinterException if an error in the print system causes the job
5991      *                          to be aborted
5992      * @see #print(JTable.PrintMode, MessageFormat, MessageFormat,
5993      *             boolean, PrintRequestAttributeSet, boolean, PrintService)
5994      * @see #getPrintable
5995      *
5996      * @since 1.5
5997      */
5998     public boolean print() throws PrinterException {
5999 
6000         return print(PrintMode.FIT_WIDTH);
6001     }
6002 
6003     /**
6004      * A convenience method that displays a printing dialog, and then prints
6005      * this <code>JTable</code> in the given printing mode,
6006      * with no header or footer text. A modal progress dialog, with an abort
6007      * option, will be shown for the duration of printing.
6008      * <p>
6009      * Note: In headless mode, no dialogs are shown and printing
6010      * occurs on the default printer.
6011      *
6012      * @param  printMode        the printing mode that the printable should use
6013      * @return true, unless printing is cancelled by the user
6014      * @throws SecurityException if this thread is not allowed to
6015      *                           initiate a print job request
6016      * @throws PrinterException if an error in the print system causes the job
6017      *                          to be aborted
6018      * @see #print(JTable.PrintMode, MessageFormat, MessageFormat,
6019      *             boolean, PrintRequestAttributeSet, boolean, PrintService)
6020      * @see #getPrintable
6021      *
6022      * @since 1.5
6023      */
6024     public boolean print(PrintMode printMode) throws PrinterException {
6025 
6026         return print(printMode, null, null);
6027     }
6028 
6029     /**
6030      * A convenience method that displays a printing dialog, and then prints
6031      * this <code>JTable</code> in the given printing mode,
6032      * with the specified header and footer text. A modal progress dialog,
6033      * with an abort option, will be shown for the duration of printing.
6034      * <p>
6035      * Note: In headless mode, no dialogs are shown and printing
6036      * occurs on the default printer.
6037      *
6038      * @param  printMode        the printing mode that the printable should use
6039      * @param  headerFormat     a <code>MessageFormat</code> specifying the text
6040      *                          to be used in printing a header,
6041      *                          or null for none
6042      * @param  footerFormat     a <code>MessageFormat</code> specifying the text
6043      *                          to be used in printing a footer,
6044      *                          or null for none
6045      * @return true, unless printing is cancelled by the user
6046      * @throws SecurityException if this thread is not allowed to
6047      *                           initiate a print job request
6048      * @throws PrinterException if an error in the print system causes the job
6049      *                          to be aborted
6050      * @see #print(JTable.PrintMode, MessageFormat, MessageFormat,
6051      *             boolean, PrintRequestAttributeSet, boolean, PrintService)
6052      * @see #getPrintable
6053      *
6054      * @since 1.5
6055      */
6056     public boolean print(PrintMode printMode,
6057                          MessageFormat headerFormat,
6058                          MessageFormat footerFormat) throws PrinterException {
6059 
6060         boolean showDialogs = !GraphicsEnvironment.isHeadless();
6061         return print(printMode, headerFormat, footerFormat,
6062                      showDialogs, null, showDialogs);
6063     }
6064 
6065     /**
6066      * Prints this table, as specified by the fully featured
6067      * {@link #print(JTable.PrintMode, MessageFormat, MessageFormat,
6068      * boolean, PrintRequestAttributeSet, boolean, PrintService) print}
6069      * method, with the default printer specified as the print service.
6070      *
6071      * @param  printMode        the printing mode that the printable should use
6072      * @param  headerFormat     a <code>MessageFormat</code> specifying the text
6073      *                          to be used in printing a header,
6074      *                          or <code>null</code> for none
6075      * @param  footerFormat     a <code>MessageFormat</code> specifying the text
6076      *                          to be used in printing a footer,
6077      *                          or <code>null</code> for none
6078      * @param  showPrintDialog  whether or not to display a print dialog
6079      * @param  attr             a <code>PrintRequestAttributeSet</code>
6080      *                          specifying any printing attributes,
6081      *                          or <code>null</code> for none
6082      * @param  interactive      whether or not to print in an interactive mode
6083      * @return true, unless printing is cancelled by the user
6084      * @throws HeadlessException if the method is asked to show a printing
6085      *                           dialog or run interactively, and
6086      *                           <code>GraphicsEnvironment.isHeadless</code>
6087      *                           returns <code>true</code>
6088      * @throws SecurityException if this thread is not allowed to
6089      *                           initiate a print job request
6090      * @throws PrinterException if an error in the print system causes the job
6091      *                          to be aborted
6092      * @see #print(JTable.PrintMode, MessageFormat, MessageFormat,
6093      *             boolean, PrintRequestAttributeSet, boolean, PrintService)
6094      * @see #getPrintable
6095      *
6096      * @since 1.5
6097      */
6098     public boolean print(PrintMode printMode,
6099                          MessageFormat headerFormat,
6100                          MessageFormat footerFormat,
6101                          boolean showPrintDialog,
6102                          PrintRequestAttributeSet attr,
6103                          boolean interactive) throws PrinterException,
6104                                                      HeadlessException {
6105 
6106         return print(printMode,
6107                      headerFormat,
6108                      footerFormat,
6109                      showPrintDialog,
6110                      attr,
6111                      interactive,
6112                      null);
6113     }
6114 
6115     /**
6116      * Prints this <code>JTable</code>. Takes steps that the majority of
6117      * developers would take in order to print a <code>JTable</code>.
6118      * In short, it prepares the table, calls <code>getPrintable</code> to
6119      * fetch an appropriate <code>Printable</code>, and then sends it to the
6120      * printer.
6121      * <p>
6122      * A <code>boolean</code> parameter allows you to specify whether or not
6123      * a printing dialog is displayed to the user. When it is, the user may
6124      * use the dialog to change the destination printer or printing attributes,
6125      * or even to cancel the print. Another two parameters allow for a
6126      * <code>PrintService</code> and printing attributes to be specified.
6127      * These parameters can be used either to provide initial values for the
6128      * print dialog, or to specify values when the dialog is not shown.
6129      * <p>
6130      * A second <code>boolean</code> parameter allows you to specify whether
6131      * or not to perform printing in an interactive mode. If <code>true</code>,
6132      * a modal progress dialog, with an abort option, is displayed for the
6133      * duration of printing . This dialog also prevents any user action which
6134      * may affect the table. However, it can not prevent the table from being
6135      * modified by code (for example, another thread that posts updates using
6136      * <code>SwingUtilities.invokeLater</code>). It is therefore the
6137      * responsibility of the developer to ensure that no other code modifies
6138      * the table in any way during printing (invalid modifications include
6139      * changes in: size, renderers, or underlying data). Printing behavior is
6140      * undefined when the table is changed during printing.
6141      * <p>
6142      * If <code>false</code> is specified for this parameter, no dialog will
6143      * be displayed and printing will begin immediately on the event-dispatch
6144      * thread. This blocks any other events, including repaints, from being
6145      * processed until printing is complete. Although this effectively prevents
6146      * the table from being changed, it doesn't provide a good user experience.
6147      * For this reason, specifying <code>false</code> is only recommended when
6148      * printing from an application with no visible GUI.
6149      * <p>
6150      * Note: Attempting to show the printing dialog or run interactively, while
6151      * in headless mode, will result in a <code>HeadlessException</code>.
6152      * <p>
6153      * Before fetching the printable, this method will gracefully terminate
6154      * editing, if necessary, to prevent an editor from showing in the printed
6155      * result. Additionally, <code>JTable</code> will prepare its renderers
6156      * during printing such that selection and focus are not indicated.
6157      * As far as customizing further how the table looks in the printout,
6158      * developers can provide custom renderers or paint code that conditionalize
6159      * on the value of {@link javax.swing.JComponent#isPaintingForPrint()}.
6160      * <p>
6161      * See {@link #getPrintable} for more description on how the table is
6162      * printed.
6163      *
6164      * @param  printMode        the printing mode that the printable should use
6165      * @param  headerFormat     a <code>MessageFormat</code> specifying the text
6166      *                          to be used in printing a header,
6167      *                          or <code>null</code> for none
6168      * @param  footerFormat     a <code>MessageFormat</code> specifying the text
6169      *                          to be used in printing a footer,
6170      *                          or <code>null</code> for none
6171      * @param  showPrintDialog  whether or not to display a print dialog
6172      * @param  attr             a <code>PrintRequestAttributeSet</code>
6173      *                          specifying any printing attributes,
6174      *                          or <code>null</code> for none
6175      * @param  interactive      whether or not to print in an interactive mode
6176      * @param  service          the destination <code>PrintService</code>,
6177      *                          or <code>null</code> to use the default printer
6178      * @return true, unless printing is cancelled by the user
6179      * @throws HeadlessException if the method is asked to show a printing
6180      *                           dialog or run interactively, and
6181      *                           <code>GraphicsEnvironment.isHeadless</code>
6182      *                           returns <code>true</code>
6183      * @throws  SecurityException if a security manager exists and its
6184      *          {@link java.lang.SecurityManager#checkPrintJobAccess}
6185      *          method disallows this thread from creating a print job request
6186      * @throws PrinterException if an error in the print system causes the job
6187      *                          to be aborted
6188      * @see #getPrintable
6189      * @see java.awt.GraphicsEnvironment#isHeadless
6190      *
6191      * @since 1.6
6192      */
6193     public boolean print(PrintMode printMode,
6194                          MessageFormat headerFormat,
6195                          MessageFormat footerFormat,
6196                          boolean showPrintDialog,
6197                          PrintRequestAttributeSet attr,
6198                          boolean interactive,
6199                          PrintService service) throws PrinterException,
6200                                                       HeadlessException {
6201 
6202         // complain early if an invalid parameter is specified for headless mode
6203         boolean isHeadless = GraphicsEnvironment.isHeadless();
6204         if (isHeadless) {
6205             if (showPrintDialog) {
6206                 throw new HeadlessException("Can't show print dialog.");
6207             }
6208 
6209             if (interactive) {
6210                 throw new HeadlessException("Can't run interactively.");
6211             }
6212         }
6213 
6214         // Get a PrinterJob.
6215         // Do this before anything with side-effects since it may throw a
6216         // security exception - in which case we don't want to do anything else.
6217         final PrinterJob job = PrinterJob.getPrinterJob();
6218 
6219         if (isEditing()) {
6220             // try to stop cell editing, and failing that, cancel it
6221             if (!getCellEditor().stopCellEditing()) {
6222                 getCellEditor().cancelCellEditing();
6223             }
6224         }
6225 
6226         if (attr == null) {
6227             attr = new HashPrintRequestAttributeSet();
6228         }
6229 
6230         final PrintingStatus printingStatus;
6231 
6232          // fetch the Printable
6233         Printable printable =
6234              getPrintable(printMode, headerFormat, footerFormat);
6235 
6236         if (interactive) {
6237             // wrap the Printable so that we can print on another thread
6238             printable = new ThreadSafePrintable(printable);
6239             printingStatus = PrintingStatus.createPrintingStatus(this, job);
6240             printable = printingStatus.createNotificationPrintable(printable);
6241         } else {
6242             // to please compiler
6243             printingStatus = null;
6244         }
6245 
6246         // set the printable on the PrinterJob
6247         job.setPrintable(printable);
6248 
6249         // if specified, set the PrintService on the PrinterJob
6250         if (service != null) {
6251             job.setPrintService(service);
6252         }
6253 
6254         // if requested, show the print dialog
6255         if (showPrintDialog && !job.printDialog(attr)) {
6256             // the user cancelled the print dialog
6257             return false;
6258         }
6259 
6260         // if not interactive, just print on this thread (no dialog)
6261         if (!interactive) {
6262             // do the printing
6263             job.print(attr);
6264 
6265             // we're done
6266             return true;
6267         }
6268 
6269         // make sure this is clear since we'll check it after
6270         printError = null;
6271 
6272         // to synchronize on
6273         final Object lock = new Object();
6274 
6275         // copied so we can access from the inner class
6276         final PrintRequestAttributeSet copyAttr = attr;
6277 
6278         // this runnable will be used to do the printing
6279         // (and save any throwables) on another thread
6280         Runnable runnable = new Runnable() {
6281             public void run() {
6282                 try {
6283                     // do the printing
6284                     job.print(copyAttr);
6285                 } catch (Throwable t) {
6286                     // save any Throwable to be rethrown
6287                     synchronized(lock) {
6288                         printError = t;
6289                     }
6290                 } finally {
6291                     // we're finished - hide the dialog
6292                     printingStatus.dispose();
6293                 }
6294             }
6295         };
6296 
6297         // start printing on another thread
6298         Thread th = new Thread(runnable);
6299         th.start();
6300 
6301         printingStatus.showModal(true);
6302 
6303         // look for any error that the printing may have generated
6304         Throwable pe;
6305         synchronized(lock) {
6306             pe = printError;
6307             printError = null;
6308         }
6309 
6310         // check the type of error and handle it
6311         if (pe != null) {
6312             // a subclass of PrinterException meaning the job was aborted,
6313             // in this case, by the user
6314             if (pe instanceof PrinterAbortException) {
6315                 return false;
6316             } else if (pe instanceof PrinterException) {
6317                 throw (PrinterException)pe;
6318             } else if (pe instanceof RuntimeException) {
6319                 throw (RuntimeException)pe;
6320             } else if (pe instanceof Error) {
6321                 throw (Error)pe;
6322             }
6323 
6324             // can not happen
6325             throw new AssertionError(pe);
6326         }
6327 
6328         return true;
6329     }
6330 
6331     /**
6332      * Return a <code>Printable</code> for use in printing this JTable.
6333      * <p>
6334      * This method is meant for those wishing to customize the default
6335      * <code>Printable</code> implementation used by <code>JTable</code>'s
6336      * <code>print</code> methods. Developers wanting simply to print the table
6337      * should use one of those methods directly.
6338      * <p>
6339      * The <code>Printable</code> can be requested in one of two printing modes.
6340      * In both modes, it spreads table rows naturally in sequence across
6341      * multiple pages, fitting as many rows as possible per page.
6342      * <code>PrintMode.NORMAL</code> specifies that the table be
6343      * printed at its current size. In this mode, there may be a need to spread
6344      * columns across pages in a similar manner to that of the rows. When the
6345      * need arises, columns are distributed in an order consistent with the
6346      * table's <code>ComponentOrientation</code>.
6347      * <code>PrintMode.FIT_WIDTH</code> specifies that the output be
6348      * scaled smaller, if necessary, to fit the table's entire width
6349      * (and thereby all columns) on each page. Width and height are scaled
6350      * equally, maintaining the aspect ratio of the output.
6351      * <p>
6352      * The <code>Printable</code> heads the portion of table on each page
6353      * with the appropriate section from the table's <code>JTableHeader</code>,
6354      * if it has one.
6355      * <p>
6356      * Header and footer text can be added to the output by providing
6357      * <code>MessageFormat</code> arguments. The printing code requests
6358      * Strings from the formats, providing a single item which may be included
6359      * in the formatted string: an <code>Integer</code> representing the current
6360      * page number.
6361      * <p>
6362      * You are encouraged to read the documentation for
6363      * <code>MessageFormat</code> as some characters, such as single-quote,
6364      * are special and need to be escaped.
6365      * <p>
6366      * Here's an example of creating a <code>MessageFormat</code> that can be
6367      * used to print "Duke's Table: Page - " and the current page number:
6368      *
6369      * <pre>
6370      *     // notice the escaping of the single quote
6371      *     // notice how the page number is included with "{0}"
6372      *     MessageFormat format = new MessageFormat("Duke''s Table: Page - {0}");
6373      * </pre>
6374      * <p>
6375      * The <code>Printable</code> constrains what it draws to the printable
6376      * area of each page that it prints. Under certain circumstances, it may
6377      * find it impossible to fit all of a page's content into that area. In
6378      * these cases the output may be clipped, but the implementation
6379      * makes an effort to do something reasonable. Here are a few situations
6380      * where this is known to occur, and how they may be handled by this
6381      * particular implementation:
6382      * <ul>
6383      *   <li>In any mode, when the header or footer text is too wide to fit
6384      *       completely in the printable area -- print as much of the text as
6385      *       possible starting from the beginning, as determined by the table's
6386      *       <code>ComponentOrientation</code>.
6387      *   <li>In any mode, when a row is too tall to fit in the
6388      *       printable area -- print the upper-most portion of the row
6389      *       and paint no lower border on the table.
6390      *   <li>In <code>PrintMode.NORMAL</code> when a column
6391      *       is too wide to fit in the printable area -- print the center
6392      *       portion of the column and leave the left and right borders
6393      *       off the table.
6394      * </ul>
6395      * <p>
6396      * It is entirely valid for this <code>Printable</code> to be wrapped
6397      * inside another in order to create complex reports and documents. You may
6398      * even request that different pages be rendered into different sized
6399      * printable areas. The implementation must be prepared to handle this
6400      * (possibly by doing its layout calculations on the fly). However,
6401      * providing different heights to each page will likely not work well
6402      * with <code>PrintMode.NORMAL</code> when it has to spread columns
6403      * across pages.
6404      * <p>
6405      * As far as customizing how the table looks in the printed result,
6406      * <code>JTable</code> itself will take care of hiding the selection
6407      * and focus during printing. For additional customizations, your
6408      * renderers or painting code can customize the look based on the value
6409      * of {@link javax.swing.JComponent#isPaintingForPrint()}
6410      * <p>
6411      * Also, <i>before</i> calling this method you may wish to <i>first</i>
6412      * modify the state of the table, such as to cancel cell editing or
6413      * have the user size the table appropriately. However, you must not
6414      * modify the state of the table <i>after</i> this <code>Printable</code>
6415      * has been fetched (invalid modifications include changes in size or
6416      * underlying data). The behavior of the returned <code>Printable</code>
6417      * is undefined once the table has been changed.
6418      *
6419      * @param  printMode     the printing mode that the printable should use
6420      * @param  headerFormat  a <code>MessageFormat</code> specifying the text to
6421      *                       be used in printing a header, or null for none
6422      * @param  footerFormat  a <code>MessageFormat</code> specifying the text to
6423      *                       be used in printing a footer, or null for none
6424      * @return a <code>Printable</code> for printing this JTable
6425      * @see #print(JTable.PrintMode, MessageFormat, MessageFormat,
6426      *             boolean, PrintRequestAttributeSet, boolean)
6427      * @see Printable
6428      * @see PrinterJob
6429      *
6430      * @since 1.5
6431      */
6432     public Printable getPrintable(PrintMode printMode,
6433                                   MessageFormat headerFormat,
6434                                   MessageFormat footerFormat) {
6435 
6436         return new TablePrintable(this, printMode, headerFormat, footerFormat);
6437     }
6438 
6439 
6440     /**
6441      * A <code>Printable</code> implementation that wraps another
6442      * <code>Printable</code>, making it safe for printing on another thread.
6443      */
6444     private class ThreadSafePrintable implements Printable {
6445 
6446         /** The delegate <code>Printable</code>. */
6447         private Printable printDelegate;
6448 
6449         /**
6450          * To communicate any return value when delegating.
6451          */
6452         private int retVal;
6453 
6454         /**
6455          * To communicate any <code>Throwable</code> when delegating.
6456          */
6457         private Throwable retThrowable;
6458 
6459         /**
6460          * Construct a <code>ThreadSafePrintable</code> around the given
6461          * delegate.
6462          *
6463          * @param printDelegate the <code>Printable</code> to delegate to
6464          */
6465         public ThreadSafePrintable(Printable printDelegate) {
6466             this.printDelegate = printDelegate;
6467         }
6468 
6469         /**
6470          * Prints the specified page into the given {@link Graphics}
6471          * context, in the specified format.
6472          * <p>
6473          * Regardless of what thread this method is called on, all calls into
6474          * the delegate will be done on the event-dispatch thread.
6475          *
6476          * @param   graphics    the context into which the page is drawn
6477          * @param   pageFormat  the size and orientation of the page being drawn
6478          * @param   pageIndex   the zero based index of the page to be drawn
6479          * @return  PAGE_EXISTS if the page is rendered successfully, or
6480          *          NO_SUCH_PAGE if a non-existent page index is specified
6481          * @throws  PrinterException if an error causes printing to be aborted
6482          */
6483         public int print(final Graphics graphics,
6484                          final PageFormat pageFormat,
6485                          final int pageIndex) throws PrinterException {
6486 
6487             // We'll use this Runnable
6488             Runnable runnable = new Runnable() {
6489                 public synchronized void run() {
6490                     try {
6491                         // call into the delegate and save the return value
6492                         retVal = printDelegate.print(graphics, pageFormat, pageIndex);
6493                     } catch (Throwable throwable) {
6494                         // save any Throwable to be rethrown
6495                         retThrowable = throwable;
6496                     } finally {
6497                         // notify the caller that we're done
6498                         notifyAll();
6499                     }
6500                 }
6501             };
6502 
6503             synchronized(runnable) {
6504                 // make sure these are initialized
6505                 retVal = -1;
6506                 retThrowable = null;
6507 
6508                 // call into the EDT
6509                 SwingUtilities.invokeLater(runnable);
6510 
6511                 // wait for the runnable to finish
6512                 while (retVal == -1 && retThrowable == null) {
6513                     try {
6514                         runnable.wait();
6515                     } catch (InterruptedException ie) {
6516                         // short process, safe to ignore interrupts
6517                     }
6518                 }
6519 
6520                 // if the delegate threw a throwable, rethrow it here
6521                 if (retThrowable != null) {
6522                     if (retThrowable instanceof PrinterException) {
6523                         throw (PrinterException)retThrowable;
6524                     } else if (retThrowable instanceof RuntimeException) {
6525                         throw (RuntimeException)retThrowable;
6526                     } else if (retThrowable instanceof Error) {
6527                         throw (Error)retThrowable;
6528                     }
6529 
6530                     // can not happen
6531                     throw new AssertionError(retThrowable);
6532                 }
6533 
6534                 return retVal;
6535             }
6536         }
6537     }
6538 
6539 
6540 /////////////////
6541 // Accessibility support
6542 ////////////////
6543 
6544     /**
6545      * Gets the AccessibleContext associated with this JTable.
6546      * For tables, the AccessibleContext takes the form of an
6547      * AccessibleJTable.
6548      * A new AccessibleJTable instance is created if necessary.
6549      *
6550      * @return an AccessibleJTable that serves as the
6551      *         AccessibleContext of this JTable
6552      */
6553     public AccessibleContext getAccessibleContext() {
6554         if (accessibleContext == null) {
6555             accessibleContext = new AccessibleJTable();
6556         }
6557         return accessibleContext;
6558     }
6559 
6560     //
6561     // *** should also implement AccessibleSelection?
6562     // *** and what's up with keyboard navigation/manipulation?
6563     //
6564     /**
6565      * This class implements accessibility support for the
6566      * <code>JTable</code> class.  It provides an implementation of the
6567      * Java Accessibility API appropriate to table user-interface elements.
6568      * <p>
6569      * <strong>Warning:</strong>
6570      * Serialized objects of this class will not be compatible with
6571      * future Swing releases. The current serialization support is
6572      * appropriate for short term storage or RMI between applications running
6573      * the same version of Swing.  As of 1.4, support for long term storage
6574      * of all JavaBeans&trade;
6575      * has been added to the <code>java.beans</code> package.
6576      * Please see {@link java.beans.XMLEncoder}.
6577      */
6578     protected class AccessibleJTable extends AccessibleJComponent
6579     implements AccessibleSelection, ListSelectionListener, TableModelListener,
6580     TableColumnModelListener, CellEditorListener, PropertyChangeListener,
6581     AccessibleExtendedTable {
6582 
6583         int previousFocusedRow;
6584         int previousFocusedCol;
6585 
6586         /**
6587          * AccessibleJTable constructor
6588          *
6589          * @since 1.5
6590          */
6591         protected AccessibleJTable() {
6592             super();
6593             JTable.this.addPropertyChangeListener(this);
6594             JTable.this.getSelectionModel().addListSelectionListener(this);
6595             TableColumnModel tcm = JTable.this.getColumnModel();
6596             tcm.addColumnModelListener(this);
6597             tcm.getSelectionModel().addListSelectionListener(this);
6598             JTable.this.getModel().addTableModelListener(this);
6599             previousFocusedRow = JTable.this.getSelectionModel().
6600                                         getLeadSelectionIndex();
6601             previousFocusedCol = JTable.this.getColumnModel().
6602                                         getSelectionModel().getLeadSelectionIndex();
6603         }
6604 
6605     // Listeners to track model, etc. changes to as to re-place the other
6606     // listeners
6607 
6608         /**
6609          * Track changes to selection model, column model, etc. so as to
6610          * be able to re-place listeners on those in order to pass on
6611          * information to the Accessibility PropertyChange mechanism
6612          */
6613         public void propertyChange(PropertyChangeEvent e) {
6614             String name = e.getPropertyName();
6615             Object oldValue = e.getOldValue();
6616             Object newValue = e.getNewValue();
6617 
6618                 // re-set tableModel listeners
6619             if (name.compareTo("model") == 0) {
6620 
6621                 if (oldValue != null && oldValue instanceof TableModel) {
6622                     ((TableModel) oldValue).removeTableModelListener(this);
6623                 }
6624                 if (newValue != null && newValue instanceof TableModel) {
6625                     ((TableModel) newValue).addTableModelListener(this);
6626                 }
6627 
6628                 // re-set selectionModel listeners
6629             } else if (name.compareTo("selectionModel") == 0) {
6630 
6631                 Object source = e.getSource();
6632                 if (source == JTable.this) {    // row selection model
6633 
6634                     if (oldValue != null &&
6635                         oldValue instanceof ListSelectionModel) {
6636                         ((ListSelectionModel) oldValue).removeListSelectionListener(this);
6637                     }
6638                     if (newValue != null &&
6639                         newValue instanceof ListSelectionModel) {
6640                         ((ListSelectionModel) newValue).addListSelectionListener(this);
6641                     }
6642 
6643                 } else if (source == JTable.this.getColumnModel()) {
6644 
6645                     if (oldValue != null &&
6646                         oldValue instanceof ListSelectionModel) {
6647                         ((ListSelectionModel) oldValue).removeListSelectionListener(this);
6648                     }
6649                     if (newValue != null &&
6650                         newValue instanceof ListSelectionModel) {
6651                         ((ListSelectionModel) newValue).addListSelectionListener(this);
6652                     }
6653 
6654                 } else {
6655                   //        System.out.println("!!! Bug in source of selectionModel propertyChangeEvent");
6656                 }
6657 
6658                 // re-set columnModel listeners
6659                 // and column's selection property listener as well
6660             } else if (name.compareTo("columnModel") == 0) {
6661 
6662                 if (oldValue != null && oldValue instanceof TableColumnModel) {
6663                     TableColumnModel tcm = (TableColumnModel) oldValue;
6664                     tcm.removeColumnModelListener(this);
6665                     tcm.getSelectionModel().removeListSelectionListener(this);
6666                 }
6667                 if (newValue != null && newValue instanceof TableColumnModel) {
6668                     TableColumnModel tcm = (TableColumnModel) newValue;
6669                     tcm.addColumnModelListener(this);
6670                     tcm.getSelectionModel().addListSelectionListener(this);
6671                 }
6672 
6673                 // re-se cellEditor listeners
6674             } else if (name.compareTo("tableCellEditor") == 0) {
6675 
6676                 if (oldValue != null && oldValue instanceof TableCellEditor) {
6677                     ((TableCellEditor) oldValue).removeCellEditorListener(this);
6678                 }
6679                 if (newValue != null && newValue instanceof TableCellEditor) {
6680                     ((TableCellEditor) newValue).addCellEditorListener(this);
6681                 }
6682             }
6683         }
6684 
6685 
6686     // Listeners to echo changes to the AccessiblePropertyChange mechanism
6687 
6688         /*
6689          * Describes a change in the accessible table model.
6690          */
6691         protected class AccessibleJTableModelChange
6692             implements AccessibleTableModelChange {
6693 
6694             protected int type;
6695             protected int firstRow;
6696             protected int lastRow;
6697             protected int firstColumn;
6698             protected int lastColumn;
6699 
6700             protected AccessibleJTableModelChange(int type, int firstRow,
6701                                                   int lastRow, int firstColumn,
6702                                                   int lastColumn) {
6703                 this.type = type;
6704                 this.firstRow = firstRow;
6705                 this.lastRow = lastRow;
6706                 this.firstColumn = firstColumn;
6707                 this.lastColumn = lastColumn;
6708             }
6709 
6710             public int getType() {
6711                 return type;
6712             }
6713 
6714             public int getFirstRow() {
6715                 return firstRow;
6716             }
6717 
6718             public int getLastRow() {
6719                 return lastRow;
6720             }
6721 
6722             public int getFirstColumn() {
6723                 return firstColumn;
6724             }
6725 
6726             public int getLastColumn() {
6727                 return lastColumn;
6728             }
6729         }
6730 
6731         /**
6732          * Track changes to the table contents
6733          */
6734         public void tableChanged(TableModelEvent e) {
6735            firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
6736                               null, null);
6737            if (e != null) {
6738                int firstColumn = e.getColumn();
6739                int lastColumn = e.getColumn();
6740                if (firstColumn == TableModelEvent.ALL_COLUMNS) {
6741                    firstColumn = 0;
6742                    lastColumn = getColumnCount() - 1;
6743                }
6744 
6745                // Fire a property change event indicating the table model
6746                // has changed.
6747                AccessibleJTableModelChange change =
6748                    new AccessibleJTableModelChange(e.getType(),
6749                                                    e.getFirstRow(),
6750                                                    e.getLastRow(),
6751                                                    firstColumn,
6752                                                    lastColumn);
6753                firePropertyChange(AccessibleContext.ACCESSIBLE_TABLE_MODEL_CHANGED,
6754                                   null, change);
6755             }
6756         }
6757 
6758         /**
6759          * Track changes to the table contents (row insertions)
6760          */
6761         public void tableRowsInserted(TableModelEvent e) {
6762            firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
6763                               null, null);
6764 
6765            // Fire a property change event indicating the table model
6766            // has changed.
6767            int firstColumn = e.getColumn();
6768            int lastColumn = e.getColumn();
6769            if (firstColumn == TableModelEvent.ALL_COLUMNS) {
6770                firstColumn = 0;
6771                lastColumn = getColumnCount() - 1;
6772            }
6773            AccessibleJTableModelChange change =
6774                new AccessibleJTableModelChange(e.getType(),
6775                                                e.getFirstRow(),
6776                                                e.getLastRow(),
6777                                                firstColumn,
6778                                                lastColumn);
6779            firePropertyChange(AccessibleContext.ACCESSIBLE_TABLE_MODEL_CHANGED,
6780                               null, change);
6781         }
6782 
6783         /**
6784          * Track changes to the table contents (row deletions)
6785          */
6786         public void tableRowsDeleted(TableModelEvent e) {
6787            firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
6788                               null, null);
6789 
6790            // Fire a property change event indicating the table model
6791            // has changed.
6792            int firstColumn = e.getColumn();
6793            int lastColumn = e.getColumn();
6794            if (firstColumn == TableModelEvent.ALL_COLUMNS) {
6795                firstColumn = 0;
6796                lastColumn = getColumnCount() - 1;
6797            }
6798            AccessibleJTableModelChange change =
6799                new AccessibleJTableModelChange(e.getType(),
6800                                                e.getFirstRow(),
6801                                                e.getLastRow(),
6802                                                firstColumn,
6803                                                lastColumn);
6804            firePropertyChange(AccessibleContext.ACCESSIBLE_TABLE_MODEL_CHANGED,
6805                               null, change);
6806         }
6807 
6808         /**
6809          * Track changes to the table contents (column insertions)
6810          */
6811         public void columnAdded(TableColumnModelEvent e) {
6812            firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
6813                               null, null);
6814 
6815            // Fire a property change event indicating the table model
6816            // has changed.
6817            int type = AccessibleTableModelChange.INSERT;
6818            AccessibleJTableModelChange change =
6819                new AccessibleJTableModelChange(type,
6820                                                0,
6821                                                0,
6822                                                e.getFromIndex(),
6823                                                e.getToIndex());
6824            firePropertyChange(AccessibleContext.ACCESSIBLE_TABLE_MODEL_CHANGED,
6825                               null, change);
6826         }
6827 
6828         /**
6829          * Track changes to the table contents (column deletions)
6830          */
6831         public void columnRemoved(TableColumnModelEvent e) {
6832            firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
6833                               null, null);
6834            // Fire a property change event indicating the table model
6835            // has changed.
6836            int type = AccessibleTableModelChange.DELETE;
6837            AccessibleJTableModelChange change =
6838                new AccessibleJTableModelChange(type,
6839                                                0,
6840                                                0,
6841                                                e.getFromIndex(),
6842                                                e.getToIndex());
6843            firePropertyChange(AccessibleContext.ACCESSIBLE_TABLE_MODEL_CHANGED,
6844                               null, change);
6845         }
6846 
6847         /**
6848          * Track changes of a column repositioning.
6849          *
6850          * @see TableColumnModelListener
6851          */
6852         public void columnMoved(TableColumnModelEvent e) {
6853            firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
6854                               null, null);
6855 
6856            // Fire property change events indicating the table model
6857            // has changed.
6858            int type = AccessibleTableModelChange.DELETE;
6859            AccessibleJTableModelChange change =
6860                new AccessibleJTableModelChange(type,
6861                                                0,
6862                                                0,
6863                                                e.getFromIndex(),
6864                                                e.getFromIndex());
6865            firePropertyChange(AccessibleContext.ACCESSIBLE_TABLE_MODEL_CHANGED,
6866                               null, change);
6867 
6868            int type2 = AccessibleTableModelChange.INSERT;
6869            AccessibleJTableModelChange change2 =
6870                new AccessibleJTableModelChange(type2,
6871                                                0,
6872                                                0,
6873                                                e.getToIndex(),
6874                                                e.getToIndex());
6875            firePropertyChange(AccessibleContext.ACCESSIBLE_TABLE_MODEL_CHANGED,
6876                               null, change2);
6877         }
6878 
6879         /**
6880          * Track changes of a column moving due to margin changes.
6881          *
6882          * @see TableColumnModelListener
6883          */
6884         public void columnMarginChanged(ChangeEvent e) {
6885            firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
6886                               null, null);
6887         }
6888 
6889         /**
6890          * Track that the selection model of the TableColumnModel changed.
6891          *
6892          * @see TableColumnModelListener
6893          */
6894         public void columnSelectionChanged(ListSelectionEvent e) {
6895             // we should now re-place our TableColumn listener
6896         }
6897 
6898         /**
6899          * Track changes to a cell's contents.
6900          *
6901          * Invoked when editing is finished. The changes are saved, the
6902          * editor object is discarded, and the cell is rendered once again.
6903          *
6904          * @see CellEditorListener
6905          */
6906         public void editingStopped(ChangeEvent e) {
6907            // it'd be great if we could figure out which cell, and pass that
6908            // somehow as a parameter
6909            firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
6910                               null, null);
6911         }
6912 
6913         /**
6914          * Invoked when editing is canceled. The editor object is discarded
6915          * and the cell is rendered once again.
6916          *
6917          * @see CellEditorListener
6918          */
6919         public void editingCanceled(ChangeEvent e) {
6920             // nothing to report, 'cause nothing changed
6921         }
6922 
6923         /**
6924          * Track changes to table cell selections
6925          */
6926         public void valueChanged(ListSelectionEvent e) {
6927             firePropertyChange(AccessibleContext.ACCESSIBLE_SELECTION_PROPERTY,
6928                                Boolean.valueOf(false), Boolean.valueOf(true));
6929 
6930             // Using lead selection index to cover both cases: node selected and node
6931             // is focused but not selected (Ctrl+up/down)
6932             int focusedRow = JTable.this.getSelectionModel().getLeadSelectionIndex();
6933             int focusedCol = JTable.this.getColumnModel().getSelectionModel().
6934                                                             getLeadSelectionIndex();
6935 
6936             if (focusedRow != previousFocusedRow ||
6937                 focusedCol != previousFocusedCol) {
6938                 Accessible oldA = getAccessibleAt(previousFocusedRow, previousFocusedCol);
6939                 Accessible newA = getAccessibleAt(focusedRow, focusedCol);
6940                 firePropertyChange(AccessibleContext.ACCESSIBLE_ACTIVE_DESCENDANT_PROPERTY,
6941                                     oldA, newA);
6942                 previousFocusedRow = focusedRow;
6943                 previousFocusedCol = focusedCol;
6944             }
6945         }
6946 
6947 
6948 
6949 
6950     // AccessibleContext support
6951 
6952         /**
6953          * Get the AccessibleSelection associated with this object.  In the
6954          * implementation of the Java Accessibility API for this class,
6955          * return this object, which is responsible for implementing the
6956          * AccessibleSelection interface on behalf of itself.
6957          *
6958          * @return this object
6959          */
6960         public AccessibleSelection getAccessibleSelection() {
6961             return this;
6962         }
6963 
6964         /**
6965          * Gets the role of this object.
6966          *
6967          * @return an instance of AccessibleRole describing the role of the
6968          * object
6969          * @see AccessibleRole
6970          */
6971         public AccessibleRole getAccessibleRole() {
6972             return AccessibleRole.TABLE;
6973         }
6974 
6975         /**
6976          * Returns the <code>Accessible</code> child, if one exists,
6977          * contained at the local coordinate <code>Point</code>.
6978          *
6979          * @param p the point defining the top-left corner of the
6980          *    <code>Accessible</code>, given in the coordinate space
6981          *    of the object's parent
6982          * @return the <code>Accessible</code>, if it exists,
6983          *    at the specified location; else <code>null</code>
6984          */
6985         public Accessible getAccessibleAt(Point p) {
6986             int column = columnAtPoint(p);
6987             int row = rowAtPoint(p);
6988 
6989             if ((column != -1) && (row != -1)) {
6990                 TableColumn aColumn = getColumnModel().getColumn(column);
6991                 TableCellRenderer renderer = aColumn.getCellRenderer();
6992                 if (renderer == null) {
6993                     Class<?> columnClass = getColumnClass(column);
6994                     renderer = getDefaultRenderer(columnClass);
6995                 }
6996                 Component component = renderer.getTableCellRendererComponent(
6997                                   JTable.this, null, false, false,
6998                                   row, column);
6999                 return new AccessibleJTableCell(JTable.this, row, column,
7000                       getAccessibleIndexAt(row, column));
7001             }
7002             return null;
7003         }
7004 
7005         /**
7006          * Returns the number of accessible children in the object.  If all
7007          * of the children of this object implement <code>Accessible</code>,
7008          * then this method should return the number of children of this object.
7009          *
7010          * @return the number of accessible children in the object
7011          */
7012         public int getAccessibleChildrenCount() {
7013             return (JTable.this.getColumnCount() * JTable.this.getRowCount());
7014         }
7015 
7016         /**
7017          * Returns the nth <code>Accessible</code> child of the object.
7018          *
7019          * @param i zero-based index of child
7020          * @return the nth Accessible child of the object
7021          */
7022         public Accessible getAccessibleChild(int i) {
7023             if (i < 0 || i >= getAccessibleChildrenCount()) {
7024                 return null;
7025             } else {
7026                 // children increase across, and then down, for tables
7027                 // (arbitrary decision)
7028                 int column = getAccessibleColumnAtIndex(i);
7029                 int row = getAccessibleRowAtIndex(i);
7030 
7031                 TableColumn aColumn = getColumnModel().getColumn(column);
7032                 TableCellRenderer renderer = aColumn.getCellRenderer();
7033                 if (renderer == null) {
7034                     Class<?> columnClass = getColumnClass(column);
7035                     renderer = getDefaultRenderer(columnClass);
7036                 }
7037                 Component component = renderer.getTableCellRendererComponent(
7038                                   JTable.this, null, false, false,
7039                                   row, column);
7040                 return new AccessibleJTableCell(JTable.this, row, column,
7041                       getAccessibleIndexAt(row, column));
7042             }
7043         }
7044 
7045     // AccessibleSelection support
7046 
7047         /**
7048          * Returns the number of <code>Accessible</code> children
7049          * currently selected.
7050          * If no children are selected, the return value will be 0.
7051          *
7052          * @return the number of items currently selected
7053          */
7054         public int getAccessibleSelectionCount() {
7055             int rowsSel = JTable.this.getSelectedRowCount();
7056             int colsSel = JTable.this.getSelectedColumnCount();
7057 
7058             if (JTable.this.cellSelectionEnabled) { // a contiguous block
7059                 return rowsSel * colsSel;
7060 
7061             } else {
7062                 // a column swath and a row swath, with a shared block
7063                 if (JTable.this.getRowSelectionAllowed() &&
7064                     JTable.this.getColumnSelectionAllowed()) {
7065                     return rowsSel * JTable.this.getColumnCount() +
7066                            colsSel * JTable.this.getRowCount() -
7067                            rowsSel * colsSel;
7068 
7069                 // just one or more rows in selection
7070                 } else if (JTable.this.getRowSelectionAllowed()) {
7071                     return rowsSel * JTable.this.getColumnCount();
7072 
7073                 // just one or more rows in selection
7074                 } else if (JTable.this.getColumnSelectionAllowed()) {
7075                     return colsSel * JTable.this.getRowCount();
7076 
7077                 } else {
7078                     return 0;    // JTable doesn't allow selections
7079                 }
7080             }
7081         }
7082 
7083         /**
7084          * Returns an <code>Accessible</code> representing the
7085          * specified selected child in the object.  If there
7086          * isn't a selection, or there are fewer children selected
7087          * than the integer passed in, the return
7088          * value will be <code>null</code>.
7089          * <p>Note that the index represents the i-th selected child, which
7090          * is different from the i-th child.
7091          *
7092          * @param i the zero-based index of selected children
7093          * @return the i-th selected child
7094          * @see #getAccessibleSelectionCount
7095          */
7096         public Accessible getAccessibleSelection(int i) {
7097             if (i < 0 || i > getAccessibleSelectionCount()) {
7098                 return null;
7099             }
7100 
7101             int rowsSel = JTable.this.getSelectedRowCount();
7102             int colsSel = JTable.this.getSelectedColumnCount();
7103             int rowIndicies[] = getSelectedRows();
7104             int colIndicies[] = getSelectedColumns();
7105             int ttlCols = JTable.this.getColumnCount();
7106             int ttlRows = JTable.this.getRowCount();
7107             int r;
7108             int c;
7109 
7110             if (JTable.this.cellSelectionEnabled) { // a contiguous block
7111                 r = rowIndicies[i / colsSel];
7112                 c = colIndicies[i % colsSel];
7113                 return getAccessibleChild((r * ttlCols) + c);
7114             } else {
7115 
7116                 // a column swath and a row swath, with a shared block
7117                 if (JTable.this.getRowSelectionAllowed() &&
7118                     JTable.this.getColumnSelectionAllowed()) {
7119 
7120                     // Situation:
7121                     //   We have a table, like the 6x3 table below,
7122                     //   wherein three colums and one row selected
7123                     //   (selected cells marked with "*", unselected "0"):
7124                     //
7125                     //            0 * 0 * * 0
7126                     //            * * * * * *
7127                     //            0 * 0 * * 0
7128                     //
7129 
7130                     // State machine below walks through the array of
7131                     // selected rows in two states: in a selected row,
7132                     // and not in one; continuing until we are in a row
7133                     // in which the ith selection exists.  Then we return
7134                     // the appropriate cell.  In the state machine, we
7135                     // always do rows above the "current" selected row first,
7136                     // then the cells in the selected row.  If we're done
7137                     // with the state machine before finding the requested
7138                     // selected child, we handle the rows below the last
7139                     // selected row at the end.
7140                     //
7141                     int curIndex = i;
7142                     final int IN_ROW = 0;
7143                     final int NOT_IN_ROW = 1;
7144                     int state = (rowIndicies[0] == 0 ? IN_ROW : NOT_IN_ROW);
7145                     int j = 0;
7146                     int prevRow = -1;
7147                     while (j < rowIndicies.length) {
7148                         switch (state) {
7149 
7150                         case IN_ROW:   // on individual row full of selections
7151                             if (curIndex < ttlCols) { // it's here!
7152                                 c = curIndex % ttlCols;
7153                                 r = rowIndicies[j];
7154                                 return getAccessibleChild((r * ttlCols) + c);
7155                             } else {                               // not here
7156                                 curIndex -= ttlCols;
7157                             }
7158                             // is the next row in table selected or not?
7159                             if (j + 1 == rowIndicies.length ||
7160                                 rowIndicies[j] != rowIndicies[j+1] - 1) {
7161                                 state = NOT_IN_ROW;
7162                                 prevRow = rowIndicies[j];
7163                             }
7164                             j++;  // we didn't return earlier, so go to next row
7165                             break;
7166 
7167                         case NOT_IN_ROW:  // sparse bunch of rows of selections
7168                             if (curIndex <
7169                                 (colsSel * (rowIndicies[j] -
7170                                 (prevRow == -1 ? 0 : (prevRow + 1))))) {
7171 
7172                                 // it's here!
7173                                 c = colIndicies[curIndex % colsSel];
7174                                 r = (j > 0 ? rowIndicies[j-1] + 1 : 0)
7175                                     + curIndex / colsSel;
7176                                 return getAccessibleChild((r * ttlCols) + c);
7177                             } else {                               // not here
7178                                 curIndex -= colsSel * (rowIndicies[j] -
7179                                 (prevRow == -1 ? 0 : (prevRow + 1)));
7180                             }
7181                             state = IN_ROW;
7182                             break;
7183                         }
7184                     }
7185                     // we got here, so we didn't find it yet; find it in
7186                     // the last sparse bunch of rows
7187                     if (curIndex <
7188                         (colsSel * (ttlRows -
7189                         (prevRow == -1 ? 0 : (prevRow + 1))))) { // it's here!
7190                         c = colIndicies[curIndex % colsSel];
7191                         r = rowIndicies[j-1] + curIndex / colsSel + 1;
7192                         return getAccessibleChild((r * ttlCols) + c);
7193                     } else {                               // not here
7194                         // we shouldn't get to this spot in the code!
7195 //                      System.out.println("Bug in AccessibleJTable.getAccessibleSelection()");
7196                     }
7197 
7198                 // one or more rows selected
7199                 } else if (JTable.this.getRowSelectionAllowed()) {
7200                     c = i % ttlCols;
7201                     r = rowIndicies[i / ttlCols];
7202                     return getAccessibleChild((r * ttlCols) + c);
7203 
7204                 // one or more columns selected
7205                 } else if (JTable.this.getColumnSelectionAllowed()) {
7206                     c = colIndicies[i % colsSel];
7207                     r = i / colsSel;
7208                     return getAccessibleChild((r * ttlCols) + c);
7209                 }
7210             }
7211             return null;
7212         }
7213 
7214         /**
7215          * Determines if the current child of this object is selected.
7216          *
7217          * @param i the zero-based index of the child in this
7218          *    <code>Accessible</code> object
7219          * @return true if the current child of this object is selected
7220          * @see AccessibleContext#getAccessibleChild
7221          */
7222         public boolean isAccessibleChildSelected(int i) {
7223             int column = getAccessibleColumnAtIndex(i);
7224             int row = getAccessibleRowAtIndex(i);
7225             return JTable.this.isCellSelected(row, column);
7226         }
7227 
7228         /**
7229          * Adds the specified <code>Accessible</code> child of the
7230          * object to the object's selection.  If the object supports
7231          * multiple selections, the specified child is added to
7232          * any existing selection, otherwise
7233          * it replaces any existing selection in the object.  If the
7234          * specified child is already selected, this method has no effect.
7235          * <p>
7236          * This method only works on <code>JTable</code>s which have
7237          * individual cell selection enabled.
7238          *
7239          * @param i the zero-based index of the child
7240          * @see AccessibleContext#getAccessibleChild
7241          */
7242         public void addAccessibleSelection(int i) {
7243             // TIGER - 4495286
7244             int column = getAccessibleColumnAtIndex(i);
7245             int row = getAccessibleRowAtIndex(i);
7246             JTable.this.changeSelection(row, column, true, false);
7247         }
7248 
7249         /**
7250          * Removes the specified child of the object from the object's
7251          * selection.  If the specified item isn't currently selected, this
7252          * method has no effect.
7253          * <p>
7254          * This method only works on <code>JTables</code> which have
7255          * individual cell selection enabled.
7256          *
7257          * @param i the zero-based index of the child
7258          * @see AccessibleContext#getAccessibleChild
7259          */
7260         public void removeAccessibleSelection(int i) {
7261             if (JTable.this.cellSelectionEnabled) {
7262                 int column = getAccessibleColumnAtIndex(i);
7263                 int row = getAccessibleRowAtIndex(i);
7264                 JTable.this.removeRowSelectionInterval(row, row);
7265                 JTable.this.removeColumnSelectionInterval(column, column);
7266             }
7267         }
7268 
7269         /**
7270          * Clears the selection in the object, so that no children in the
7271          * object are selected.
7272          */
7273         public void clearAccessibleSelection() {
7274             JTable.this.clearSelection();
7275         }
7276 
7277         /**
7278          * Causes every child of the object to be selected, but only
7279          * if the <code>JTable</code> supports multiple selections,
7280          * and if individual cell selection is enabled.
7281          */
7282         public void selectAllAccessibleSelection() {
7283             if (JTable.this.cellSelectionEnabled) {
7284                 JTable.this.selectAll();
7285             }
7286         }
7287 
7288         // begin AccessibleExtendedTable implementation -------------
7289 
7290         /**
7291          * Returns the row number of an index in the table.
7292          *
7293          * @param index the zero-based index in the table
7294          * @return the zero-based row of the table if one exists;
7295          * otherwise -1.
7296          * @since 1.4
7297          */
7298         public int getAccessibleRow(int index) {
7299             return getAccessibleRowAtIndex(index);
7300         }
7301 
7302         /**
7303          * Returns the column number of an index in the table.
7304          *
7305          * @param index the zero-based index in the table
7306          * @return the zero-based column of the table if one exists;
7307          * otherwise -1.
7308          * @since 1.4
7309          */
7310         public int getAccessibleColumn(int index) {
7311             return getAccessibleColumnAtIndex(index);
7312         }
7313 
7314         /**
7315          * Returns the index at a row and column in the table.
7316          *
7317          * @param r zero-based row of the table
7318          * @param c zero-based column of the table
7319          * @return the zero-based index in the table if one exists;
7320          * otherwise -1.
7321          * @since 1.4
7322          */
7323         public int getAccessibleIndex(int r, int c) {
7324             return getAccessibleIndexAt(r, c);
7325         }
7326 
7327         // end of AccessibleExtendedTable implementation ------------
7328 
7329         // start of AccessibleTable implementation ------------------
7330 
7331         private Accessible caption;
7332         private Accessible summary;
7333         private Accessible [] rowDescription;
7334         private Accessible [] columnDescription;
7335 
7336         /**
7337          * Gets the <code>AccessibleTable</code> associated with this
7338          * object.  In the implementation of the Java Accessibility
7339          * API for this class, return this object, which is responsible
7340          * for implementing the <code>AccessibleTables</code> interface
7341          * on behalf of itself.
7342          *
7343          * @return this object
7344          * @since 1.3
7345          */
7346         public AccessibleTable getAccessibleTable() {
7347             return this;
7348         }
7349 
7350         /**
7351          * Returns the caption for the table.
7352          *
7353          * @return the caption for the table
7354          * @since 1.3
7355          */
7356         public Accessible getAccessibleCaption() {
7357             return this.caption;
7358         }
7359 
7360         /**
7361          * Sets the caption for the table.
7362          *
7363          * @param a the caption for the table
7364          * @since 1.3
7365          */
7366         public void setAccessibleCaption(Accessible a) {
7367             Accessible oldCaption = caption;
7368             this.caption = a;
7369             firePropertyChange(AccessibleContext.ACCESSIBLE_TABLE_CAPTION_CHANGED,
7370                                oldCaption, this.caption);
7371         }
7372 
7373         /**
7374          * Returns the summary description of the table.
7375          *
7376          * @return the summary description of the table
7377          * @since 1.3
7378          */
7379         public Accessible getAccessibleSummary() {
7380             return this.summary;
7381         }
7382 
7383         /**
7384          * Sets the summary description of the table.
7385          *
7386          * @param a the summary description of the table
7387          * @since 1.3
7388          */
7389         public void setAccessibleSummary(Accessible a) {
7390             Accessible oldSummary = summary;
7391             this.summary = a;
7392             firePropertyChange(AccessibleContext.ACCESSIBLE_TABLE_SUMMARY_CHANGED,
7393                                oldSummary, this.summary);
7394         }
7395 
7396         /*
7397          * Returns the total number of rows in this table.
7398          *
7399          * @return the total number of rows in this table
7400          */
7401         public int getAccessibleRowCount() {
7402             return JTable.this.getRowCount();
7403         }
7404 
7405         /*
7406          * Returns the total number of columns in the table.
7407          *
7408          * @return the total number of columns in the table
7409          */
7410         public int getAccessibleColumnCount() {
7411             return JTable.this.getColumnCount();
7412         }
7413 
7414         /*
7415          * Returns the <code>Accessible</code> at a specified row
7416          * and column in the table.
7417          *
7418          * @param r zero-based row of the table
7419          * @param c zero-based column of the table
7420          * @return the <code>Accessible</code> at the specified row and column
7421          * in the table
7422          */
7423         public Accessible getAccessibleAt(int r, int c) {
7424             return getAccessibleChild((r * getAccessibleColumnCount()) + c);
7425         }
7426 
7427         /**
7428          * Returns the number of rows occupied by the <code>Accessible</code>
7429          * at a specified row and column in the table.
7430          *
7431          * @return the number of rows occupied by the <code>Accessible</code>
7432          *     at a specified row and column in the table
7433          * @since 1.3
7434          */
7435         public int getAccessibleRowExtentAt(int r, int c) {
7436             return 1;
7437         }
7438 
7439         /**
7440          * Returns the number of columns occupied by the
7441          * <code>Accessible</code> at a given (row, column).
7442          *
7443          * @return the number of columns occupied by the <code>Accessible</code>
7444          *     at a specified row and column in the table
7445          * @since 1.3
7446          */
7447         public int getAccessibleColumnExtentAt(int r, int c) {
7448             return 1;
7449         }
7450 
7451         /**
7452          * Returns the row headers as an <code>AccessibleTable</code>.
7453          *
7454          * @return an <code>AccessibleTable</code> representing the row
7455          * headers
7456          * @since 1.3
7457          */
7458         public AccessibleTable getAccessibleRowHeader() {
7459             // row headers are not supported
7460             return null;
7461         }
7462 
7463         /**
7464          * Sets the row headers as an <code>AccessibleTable</code>.
7465          *
7466          * @param a an <code>AccessibleTable</code> representing the row
7467          *  headers
7468          * @since 1.3
7469          */
7470         public void setAccessibleRowHeader(AccessibleTable a) {
7471             // row headers are not supported
7472         }
7473 
7474         /**
7475          * Returns the column headers as an <code>AccessibleTable</code>.
7476          *
7477          *  @return an <code>AccessibleTable</code> representing the column
7478          *          headers, or <code>null</code> if the table header is
7479          *          <code>null</code>
7480          * @since 1.3
7481          */
7482         public AccessibleTable getAccessibleColumnHeader() {
7483             JTableHeader header = JTable.this.getTableHeader();
7484             return header == null ? null : new AccessibleTableHeader(header);
7485         }
7486 
7487         /*
7488          * Private class representing a table column header
7489          */
7490         private class AccessibleTableHeader implements AccessibleTable {
7491             private JTableHeader header;
7492             private TableColumnModel headerModel;
7493 
7494             AccessibleTableHeader(JTableHeader header) {
7495                 this.header = header;
7496                 this.headerModel = header.getColumnModel();
7497             }
7498 
7499             /**
7500              * Returns the caption for the table.
7501              *
7502              * @return the caption for the table
7503              */
7504             public Accessible getAccessibleCaption() { return null; }
7505 
7506 
7507             /**
7508              * Sets the caption for the table.
7509              *
7510              * @param a the caption for the table
7511              */
7512             public void setAccessibleCaption(Accessible a) {}
7513 
7514             /**
7515              * Returns the summary description of the table.
7516              *
7517              * @return the summary description of the table
7518              */
7519             public Accessible getAccessibleSummary() { return null; }
7520 
7521             /**
7522              * Sets the summary description of the table
7523              *
7524              * @param a the summary description of the table
7525              */
7526             public void setAccessibleSummary(Accessible a) {}
7527 
7528             /**
7529              * Returns the number of rows in the table.
7530              *
7531              * @return the number of rows in the table
7532              */
7533             public int getAccessibleRowCount() { return 1; }
7534 
7535             /**
7536              * Returns the number of columns in the table.
7537              *
7538              * @return the number of columns in the table
7539              */
7540             public int getAccessibleColumnCount() {
7541                 return headerModel.getColumnCount();
7542             }
7543 
7544             /**
7545              * Returns the Accessible at a specified row and column
7546              * in the table.
7547              *
7548              * @param row zero-based row of the table
7549              * @param column zero-based column of the table
7550              * @return the Accessible at the specified row and column
7551              */
7552             public Accessible getAccessibleAt(int row, int column) {
7553 
7554 
7555                 // TIGER - 4715503
7556                 TableColumn aColumn = headerModel.getColumn(column);
7557                 TableCellRenderer renderer = aColumn.getHeaderRenderer();
7558                 if (renderer == null) {
7559                     renderer = header.getDefaultRenderer();
7560                 }
7561                 Component component = renderer.getTableCellRendererComponent(
7562                                   header.getTable(),
7563                                   aColumn.getHeaderValue(), false, false,
7564                                   -1, column);
7565 
7566                 return new AccessibleJTableHeaderCell(row, column,
7567                                                       JTable.this.getTableHeader(),
7568                                                       component);
7569             }
7570 
7571             /**
7572              * Returns the number of rows occupied by the Accessible at
7573              * a specified row and column in the table.
7574              *
7575              * @return the number of rows occupied by the Accessible at a
7576              * given specified (row, column)
7577              */
7578             public int getAccessibleRowExtentAt(int r, int c) { return 1; }
7579 
7580             /**
7581              * Returns the number of columns occupied by the Accessible at
7582              * a specified row and column in the table.
7583              *
7584              * @return the number of columns occupied by the Accessible at a
7585              * given specified row and column
7586              */
7587             public int getAccessibleColumnExtentAt(int r, int c) { return 1; }
7588 
7589             /**
7590              * Returns the row headers as an AccessibleTable.
7591              *
7592              * @return an AccessibleTable representing the row
7593              * headers
7594              */
7595             public AccessibleTable getAccessibleRowHeader() { return null; }
7596 
7597             /**
7598              * Sets the row headers.
7599              *
7600              * @param table an AccessibleTable representing the
7601              * row headers
7602              */
7603             public void setAccessibleRowHeader(AccessibleTable table) {}
7604 
7605             /**
7606              * Returns the column headers as an AccessibleTable.
7607              *
7608              * @return an AccessibleTable representing the column
7609              * headers
7610              */
7611             public AccessibleTable getAccessibleColumnHeader() { return null; }
7612 
7613             /**
7614              * Sets the column headers.
7615              *
7616              * @param table an AccessibleTable representing the
7617              * column headers
7618              * @since 1.3
7619              */
7620             public void setAccessibleColumnHeader(AccessibleTable table) {}
7621 
7622             /**
7623              * Returns the description of the specified row in the table.
7624              *
7625              * @param r zero-based row of the table
7626              * @return the description of the row
7627              * @since 1.3
7628              */
7629             public Accessible getAccessibleRowDescription(int r) { return null; }
7630 
7631             /**
7632              * Sets the description text of the specified row of the table.
7633              *
7634              * @param r zero-based row of the table
7635              * @param a the description of the row
7636              * @since 1.3
7637              */
7638             public void setAccessibleRowDescription(int r, Accessible a) {}
7639 
7640             /**
7641              * Returns the description text of the specified column in the table.
7642              *
7643              * @param c zero-based column of the table
7644              * @return the text description of the column
7645              * @since 1.3
7646              */
7647             public Accessible getAccessibleColumnDescription(int c) { return null; }
7648 
7649             /**
7650              * Sets the description text of the specified column in the table.
7651              *
7652              * @param c zero-based column of the table
7653              * @param a the text description of the column
7654              * @since 1.3
7655              */
7656             public void setAccessibleColumnDescription(int c, Accessible a) {}
7657 
7658             /**
7659              * Returns a boolean value indicating whether the accessible at
7660              * a specified row and column is selected.
7661              *
7662              * @param r zero-based row of the table
7663              * @param c zero-based column of the table
7664              * @return the boolean value true if the accessible at the
7665              * row and column is selected. Otherwise, the boolean value
7666              * false
7667              * @since 1.3
7668              */
7669             public boolean isAccessibleSelected(int r, int c) { return false; }
7670 
7671             /**
7672              * Returns a boolean value indicating whether the specified row
7673              * is selected.
7674              *
7675              * @param r zero-based row of the table
7676              * @return the boolean value true if the specified row is selected.
7677              * Otherwise, false.
7678              * @since 1.3
7679              */
7680             public boolean isAccessibleRowSelected(int r) { return false; }
7681 
7682             /**
7683              * Returns a boolean value indicating whether the specified column
7684              * is selected.
7685              *
7686              * @param c zero-based column of the table
7687              * @return the boolean value true if the specified column is selected.
7688              * Otherwise, false.
7689              * @since 1.3
7690              */
7691             public boolean isAccessibleColumnSelected(int c) { return false; }
7692 
7693             /**
7694              * Returns the selected rows in a table.
7695              *
7696              * @return an array of selected rows where each element is a
7697              * zero-based row of the table
7698              * @since 1.3
7699              */
7700             public int [] getSelectedAccessibleRows() { return new int[0]; }
7701 
7702             /**
7703              * Returns the selected columns in a table.
7704              *
7705              * @return an array of selected columns where each element is a
7706              * zero-based column of the table
7707              * @since 1.3
7708              */
7709             public int [] getSelectedAccessibleColumns() { return new int[0]; }
7710         }
7711 
7712 
7713         /**
7714          * Sets the column headers as an <code>AccessibleTable</code>.
7715          *
7716          * @param a an <code>AccessibleTable</code> representing the
7717          * column headers
7718          * @since 1.3
7719          */
7720         public void setAccessibleColumnHeader(AccessibleTable a) {
7721             // XXX not implemented
7722         }
7723 
7724         /**
7725          * Returns the description of the specified row in the table.
7726          *
7727          * @param r zero-based row of the table
7728          * @return the description of the row
7729          * @since 1.3
7730          */
7731         public Accessible getAccessibleRowDescription(int r) {
7732             if (r < 0 || r >= getAccessibleRowCount()) {
7733                 throw new IllegalArgumentException(Integer.toString(r));
7734             }
7735             if (rowDescription == null) {
7736                 return null;
7737             } else {
7738                 return rowDescription[r];
7739             }
7740         }
7741 
7742         /**
7743          * Sets the description text of the specified row of the table.
7744          *
7745          * @param r zero-based row of the table
7746          * @param a the description of the row
7747          * @since 1.3
7748          */
7749         public void setAccessibleRowDescription(int r, Accessible a) {
7750             if (r < 0 || r >= getAccessibleRowCount()) {
7751                 throw new IllegalArgumentException(Integer.toString(r));
7752             }
7753             if (rowDescription == null) {
7754                 int numRows = getAccessibleRowCount();
7755                 rowDescription = new Accessible[numRows];
7756             }
7757             rowDescription[r] = a;
7758         }
7759 
7760         /**
7761          * Returns the description of the specified column in the table.
7762          *
7763          * @param c zero-based column of the table
7764          * @return the description of the column
7765          * @since 1.3
7766          */
7767         public Accessible getAccessibleColumnDescription(int c) {
7768             if (c < 0 || c >= getAccessibleColumnCount()) {
7769                 throw new IllegalArgumentException(Integer.toString(c));
7770             }
7771             if (columnDescription == null) {
7772                 return null;
7773             } else {
7774                 return columnDescription[c];
7775             }
7776         }
7777 
7778         /**
7779          * Sets the description text of the specified column of the table.
7780          *
7781          * @param c zero-based column of the table
7782          * @param a the description of the column
7783          * @since 1.3
7784          */
7785         public void setAccessibleColumnDescription(int c, Accessible a) {
7786             if (c < 0 || c >= getAccessibleColumnCount()) {
7787                 throw new IllegalArgumentException(Integer.toString(c));
7788             }
7789             if (columnDescription == null) {
7790                 int numColumns = getAccessibleColumnCount();
7791                 columnDescription = new Accessible[numColumns];
7792             }
7793             columnDescription[c] = a;
7794         }
7795 
7796         /**
7797          * Returns a boolean value indicating whether the accessible at a
7798          * given (row, column) is selected.
7799          *
7800          * @param r zero-based row of the table
7801          * @param c zero-based column of the table
7802          * @return the boolean value true if the accessible at (row, column)
7803          *     is selected; otherwise, the boolean value false
7804          * @since 1.3
7805          */
7806         public boolean isAccessibleSelected(int r, int c) {
7807             return JTable.this.isCellSelected(r, c);
7808         }
7809 
7810         /**
7811          * Returns a boolean value indicating whether the specified row
7812          * is selected.
7813          *
7814          * @param r zero-based row of the table
7815          * @return the boolean value true if the specified row is selected;
7816          *     otherwise, false
7817          * @since 1.3
7818          */
7819         public boolean isAccessibleRowSelected(int r) {
7820             return JTable.this.isRowSelected(r);
7821         }
7822 
7823         /**
7824          * Returns a boolean value indicating whether the specified column
7825          * is selected.
7826          *
7827          * @param c zero-based column of the table
7828          * @return the boolean value true if the specified column is selected;
7829          *     otherwise, false
7830          * @since 1.3
7831          */
7832         public boolean isAccessibleColumnSelected(int c) {
7833             return JTable.this.isColumnSelected(c);
7834         }
7835 
7836         /**
7837          * Returns the selected rows in a table.
7838          *
7839          * @return an array of selected rows where each element is a
7840          *     zero-based row of the table
7841          * @since 1.3
7842          */
7843         public int [] getSelectedAccessibleRows() {
7844             return JTable.this.getSelectedRows();
7845         }
7846 
7847         /**
7848          * Returns the selected columns in a table.
7849          *
7850          * @return an array of selected columns where each element is a
7851          *     zero-based column of the table
7852          * @since 1.3
7853          */
7854         public int [] getSelectedAccessibleColumns() {
7855             return JTable.this.getSelectedColumns();
7856         }
7857 
7858         /**
7859          * Returns the row at a given index into the table.
7860          *
7861          * @param i zero-based index into the table
7862          * @return the row at a given index
7863          * @since 1.3
7864          */
7865         public int getAccessibleRowAtIndex(int i) {
7866             int columnCount = getAccessibleColumnCount();
7867             if (columnCount == 0) {
7868                 return -1;
7869             } else {
7870                 return (i / columnCount);
7871             }
7872         }
7873 
7874         /**
7875          * Returns the column at a given index into the table.
7876          *
7877          * @param i zero-based index into the table
7878          * @return the column at a given index
7879          * @since 1.3
7880          */
7881         public int getAccessibleColumnAtIndex(int i) {
7882             int columnCount = getAccessibleColumnCount();
7883             if (columnCount == 0) {
7884                 return -1;
7885             } else {
7886                 return (i % columnCount);
7887             }
7888         }
7889 
7890         /**
7891          * Returns the index at a given (row, column) in the table.
7892          *
7893          * @param r zero-based row of the table
7894          * @param c zero-based column of the table
7895          * @return the index into the table
7896          * @since 1.3
7897          */
7898         public int getAccessibleIndexAt(int r, int c) {
7899             return ((r * getAccessibleColumnCount()) + c);
7900         }
7901 
7902         // end of AccessibleTable implementation --------------------
7903 
7904         /**
7905          * The class provides an implementation of the Java Accessibility
7906          * API appropriate to table cells.
7907          */
7908         protected class AccessibleJTableCell extends AccessibleContext
7909             implements Accessible, AccessibleComponent {
7910 
7911             private JTable parent;
7912             private int row;
7913             private int column;
7914             private int index;
7915 
7916             /**
7917              *  Constructs an <code>AccessibleJTableHeaderEntry</code>.
7918              * @since 1.4
7919              */
7920             public AccessibleJTableCell(JTable t, int r, int c, int i) {
7921                 parent = t;
7922                 row = r;
7923                 column = c;
7924                 index = i;
7925                 this.setAccessibleParent(parent);
7926             }
7927 
7928             /**
7929              * Gets the <code>AccessibleContext</code> associated with this
7930              * component. In the implementation of the Java Accessibility
7931              * API for this class, return this object, which is its own
7932              * <code>AccessibleContext</code>.
7933              *
7934              * @return this object
7935              */
7936             public AccessibleContext getAccessibleContext() {
7937                 return this;
7938             }
7939 
7940             /**
7941              * Gets the AccessibleContext for the table cell renderer.
7942              *
7943              * @return the <code>AccessibleContext</code> for the table
7944              * cell renderer if one exists;
7945              * otherwise, returns <code>null</code>.
7946              * @since 1.6
7947              */
7948             protected AccessibleContext getCurrentAccessibleContext() {
7949                 TableColumn aColumn = getColumnModel().getColumn(column);
7950                 TableCellRenderer renderer = aColumn.getCellRenderer();
7951                 if (renderer == null) {
7952                     Class<?> columnClass = getColumnClass(column);
7953                     renderer = getDefaultRenderer(columnClass);
7954                 }
7955                 Component component = renderer.getTableCellRendererComponent(
7956                                   JTable.this, getValueAt(row, column),
7957                                   false, false, row, column);
7958                 if (component instanceof Accessible) {
7959                     return component.getAccessibleContext();
7960                 } else {
7961                     return null;
7962                 }
7963             }
7964 
7965             /**
7966              * Gets the table cell renderer component.
7967              *
7968              * @return the table cell renderer component if one exists;
7969              * otherwise, returns <code>null</code>.
7970              * @since 1.6
7971              */
7972             protected Component getCurrentComponent() {
7973                 TableColumn aColumn = getColumnModel().getColumn(column);
7974                 TableCellRenderer renderer = aColumn.getCellRenderer();
7975                 if (renderer == null) {
7976                     Class<?> columnClass = getColumnClass(column);
7977                     renderer = getDefaultRenderer(columnClass);
7978                 }
7979                 return renderer.getTableCellRendererComponent(
7980                                   JTable.this, null, false, false,
7981                                   row, column);
7982             }
7983 
7984         // AccessibleContext methods
7985 
7986             /**
7987              * Gets the accessible name of this object.
7988              *
7989              * @return the localized name of the object; <code>null</code>
7990              *     if this object does not have a name
7991              */
7992             public String getAccessibleName() {
7993                 AccessibleContext ac = getCurrentAccessibleContext();
7994                 if (ac != null) {
7995                     String name = ac.getAccessibleName();
7996                     if ((name != null) && (name != "")) {
7997                         // return the cell renderer's AccessibleName
7998                         return name;
7999                     }
8000                 }
8001                 if ((accessibleName != null) && (accessibleName != "")) {
8002                     return accessibleName;
8003                 } else {
8004                     // fall back to the client property
8005                     return (String)getClientProperty(AccessibleContext.ACCESSIBLE_NAME_PROPERTY);
8006                 }
8007             }
8008 
8009             /**
8010              * Sets the localized accessible name of this object.
8011              *
8012              * @param s the new localized name of the object
8013              */
8014             public void setAccessibleName(String s) {
8015                 AccessibleContext ac = getCurrentAccessibleContext();
8016                 if (ac != null) {
8017                     ac.setAccessibleName(s);
8018                 } else {
8019                     super.setAccessibleName(s);
8020                 }
8021             }
8022 
8023             //
8024             // *** should check toolTip text for desc. (needs MouseEvent)
8025             //
8026             /**
8027              * Gets the accessible description of this object.
8028              *
8029              * @return the localized description of the object;
8030              *     <code>null</code> if this object does not have
8031              *     a description
8032              */
8033             public String getAccessibleDescription() {
8034                 AccessibleContext ac = getCurrentAccessibleContext();
8035                 if (ac != null) {
8036                     return ac.getAccessibleDescription();
8037                 } else {
8038                     return super.getAccessibleDescription();
8039                 }
8040             }
8041 
8042             /**
8043              * Sets the accessible description of this object.
8044              *
8045              * @param s the new localized description of the object
8046              */
8047             public void setAccessibleDescription(String s) {
8048                 AccessibleContext ac = getCurrentAccessibleContext();
8049                 if (ac != null) {
8050                     ac.setAccessibleDescription(s);
8051                 } else {
8052                     super.setAccessibleDescription(s);
8053                 }
8054             }
8055 
8056             /**
8057              * Gets the role of this object.
8058              *
8059              * @return an instance of <code>AccessibleRole</code>
8060              *      describing the role of the object
8061              * @see AccessibleRole
8062              */
8063             public AccessibleRole getAccessibleRole() {
8064                 AccessibleContext ac = getCurrentAccessibleContext();
8065                 if (ac != null) {
8066                     return ac.getAccessibleRole();
8067                 } else {
8068                     return AccessibleRole.UNKNOWN;
8069                 }
8070             }
8071 
8072             /**
8073              * Gets the state set of this object.
8074              *
8075              * @return an instance of <code>AccessibleStateSet</code>
8076              *     containing the current state set of the object
8077              * @see AccessibleState
8078              */
8079             public AccessibleStateSet getAccessibleStateSet() {
8080                 AccessibleContext ac = getCurrentAccessibleContext();
8081                 AccessibleStateSet as = null;
8082 
8083                 if (ac != null) {
8084                     as = ac.getAccessibleStateSet();
8085                 }
8086                 if (as == null) {
8087                     as = new AccessibleStateSet();
8088                 }
8089                 Rectangle rjt = JTable.this.getVisibleRect();
8090                 Rectangle rcell = JTable.this.getCellRect(row, column, false);
8091                 if (rjt.intersects(rcell)) {
8092                     as.add(AccessibleState.SHOWING);
8093                 } else {
8094                     if (as.contains(AccessibleState.SHOWING)) {
8095                          as.remove(AccessibleState.SHOWING);
8096                     }
8097                 }
8098                 if (parent.isCellSelected(row, column)) {
8099                     as.add(AccessibleState.SELECTED);
8100                 } else if (as.contains(AccessibleState.SELECTED)) {
8101                     as.remove(AccessibleState.SELECTED);
8102                 }
8103                 if ((row == getSelectedRow()) && (column == getSelectedColumn())) {
8104                     as.add(AccessibleState.ACTIVE);
8105                 }
8106                 as.add(AccessibleState.TRANSIENT);
8107                 return as;
8108             }
8109 
8110             /**
8111              * Gets the <code>Accessible</code> parent of this object.
8112              *
8113              * @return the Accessible parent of this object;
8114              *     <code>null</code> if this object does not
8115              *     have an <code>Accessible</code> parent
8116              */
8117             public Accessible getAccessibleParent() {
8118                 return parent;
8119             }
8120 
8121             /**
8122              * Gets the index of this object in its accessible parent.
8123              *
8124              * @return the index of this object in its parent; -1 if this
8125              *     object does not have an accessible parent
8126              * @see #getAccessibleParent
8127              */
8128             public int getAccessibleIndexInParent() {
8129                 return index;
8130             }
8131 
8132             /**
8133              * Returns the number of accessible children in the object.
8134              *
8135              * @return the number of accessible children in the object
8136              */
8137             public int getAccessibleChildrenCount() {
8138                 AccessibleContext ac = getCurrentAccessibleContext();
8139                 if (ac != null) {
8140                     return ac.getAccessibleChildrenCount();
8141                 } else {
8142                     return 0;
8143                 }
8144             }
8145 
8146             /**
8147              * Returns the specified <code>Accessible</code> child of the
8148              * object.
8149              *
8150              * @param i zero-based index of child
8151              * @return the <code>Accessible</code> child of the object
8152              */
8153             public Accessible getAccessibleChild(int i) {
8154                 AccessibleContext ac = getCurrentAccessibleContext();
8155                 if (ac != null) {
8156                     Accessible accessibleChild = ac.getAccessibleChild(i);
8157                     ac.setAccessibleParent(this);
8158                     return accessibleChild;
8159                 } else {
8160                     return null;
8161                 }
8162             }
8163 
8164             /**
8165              * Gets the locale of the component. If the component
8166              * does not have a locale, then the locale of its parent
8167              * is returned.
8168              *
8169              * @return this component's locale; if this component does
8170              *    not have a locale, the locale of its parent is returned
8171              * @exception IllegalComponentStateException if the
8172              *    <code>Component</code> does not have its own locale
8173              *    and has not yet been added to a containment hierarchy
8174              *    such that the locale can be determined from the
8175              *    containing parent
8176              * @see #setLocale
8177              */
8178             public Locale getLocale() {
8179                 AccessibleContext ac = getCurrentAccessibleContext();
8180                 if (ac != null) {
8181                     return ac.getLocale();
8182                 } else {
8183                     return null;
8184                 }
8185             }
8186 
8187             /**
8188              * Adds a <code>PropertyChangeListener</code> to the listener list.
8189              * The listener is registered for all properties.
8190              *
8191              * @param l  the <code>PropertyChangeListener</code>
8192              *     to be added
8193              */
8194             public void addPropertyChangeListener(PropertyChangeListener l) {
8195                 AccessibleContext ac = getCurrentAccessibleContext();
8196                 if (ac != null) {
8197                     ac.addPropertyChangeListener(l);
8198                 } else {
8199                     super.addPropertyChangeListener(l);
8200                 }
8201             }
8202 
8203             /**
8204              * Removes a <code>PropertyChangeListener</code> from the
8205              * listener list. This removes a <code>PropertyChangeListener</code>
8206              * that was registered for all properties.
8207              *
8208              * @param l  the <code>PropertyChangeListener</code>
8209              *    to be removed
8210              */
8211             public void removePropertyChangeListener(PropertyChangeListener l) {
8212                 AccessibleContext ac = getCurrentAccessibleContext();
8213                 if (ac != null) {
8214                     ac.removePropertyChangeListener(l);
8215                 } else {
8216                     super.removePropertyChangeListener(l);
8217                 }
8218             }
8219 
8220             /**
8221              * Gets the <code>AccessibleAction</code> associated with this
8222              * object if one exists.  Otherwise returns <code>null</code>.
8223              *
8224              * @return the <code>AccessibleAction</code>, or <code>null</code>
8225              */
8226             public AccessibleAction getAccessibleAction() {
8227                 return getCurrentAccessibleContext().getAccessibleAction();
8228             }
8229 
8230             /**
8231              * Gets the <code>AccessibleComponent</code> associated with
8232              * this object if one exists.  Otherwise returns <code>null</code>.
8233              *
8234              * @return the <code>AccessibleComponent</code>, or
8235              *    <code>null</code>
8236              */
8237             public AccessibleComponent getAccessibleComponent() {
8238                 return this; // to override getBounds()
8239             }
8240 
8241             /**
8242              * Gets the <code>AccessibleSelection</code> associated with
8243              * this object if one exists.  Otherwise returns <code>null</code>.
8244              *
8245              * @return the <code>AccessibleSelection</code>, or
8246              *    <code>null</code>
8247              */
8248             public AccessibleSelection getAccessibleSelection() {
8249                 return getCurrentAccessibleContext().getAccessibleSelection();
8250             }
8251 
8252             /**
8253              * Gets the <code>AccessibleText</code> associated with this
8254              * object if one exists.  Otherwise returns <code>null</code>.
8255              *
8256              * @return the <code>AccessibleText</code>, or <code>null</code>
8257              */
8258             public AccessibleText getAccessibleText() {
8259                 return getCurrentAccessibleContext().getAccessibleText();
8260             }
8261 
8262             /**
8263              * Gets the <code>AccessibleValue</code> associated with
8264              * this object if one exists.  Otherwise returns <code>null</code>.
8265              *
8266              * @return the <code>AccessibleValue</code>, or <code>null</code>
8267              */
8268             public AccessibleValue getAccessibleValue() {
8269                 return getCurrentAccessibleContext().getAccessibleValue();
8270             }
8271 
8272 
8273         // AccessibleComponent methods
8274 
8275             /**
8276              * Gets the background color of this object.
8277              *
8278              * @return the background color, if supported, of the object;
8279              *     otherwise, <code>null</code>
8280              */
8281             public Color getBackground() {
8282                 AccessibleContext ac = getCurrentAccessibleContext();
8283                 if (ac instanceof AccessibleComponent) {
8284                     return ((AccessibleComponent) ac).getBackground();
8285                 } else {
8286                     Component c = getCurrentComponent();
8287                     if (c != null) {
8288                         return c.getBackground();
8289                     } else {
8290                         return null;
8291                     }
8292                 }
8293             }
8294 
8295             /**
8296              * Sets the background color of this object.
8297              *
8298              * @param c the new <code>Color</code> for the background
8299              */
8300             public void setBackground(Color c) {
8301                 AccessibleContext ac = getCurrentAccessibleContext();
8302                 if (ac instanceof AccessibleComponent) {
8303                     ((AccessibleComponent) ac).setBackground(c);
8304                 } else {
8305                     Component cp = getCurrentComponent();
8306                     if (cp != null) {
8307                         cp.setBackground(c);
8308                     }
8309                 }
8310             }
8311 
8312             /**
8313              * Gets the foreground color of this object.
8314              *
8315              * @return the foreground color, if supported, of the object;
8316              *     otherwise, <code>null</code>
8317              */
8318             public Color getForeground() {
8319                 AccessibleContext ac = getCurrentAccessibleContext();
8320                 if (ac instanceof AccessibleComponent) {
8321                     return ((AccessibleComponent) ac).getForeground();
8322                 } else {
8323                     Component c = getCurrentComponent();
8324                     if (c != null) {
8325                         return c.getForeground();
8326                     } else {
8327                         return null;
8328                     }
8329                 }
8330             }
8331 
8332             /**
8333              * Sets the foreground color of this object.
8334              *
8335              * @param c the new <code>Color</code> for the foreground
8336              */
8337             public void setForeground(Color c) {
8338                 AccessibleContext ac = getCurrentAccessibleContext();
8339                 if (ac instanceof AccessibleComponent) {
8340                     ((AccessibleComponent) ac).setForeground(c);
8341                 } else {
8342                     Component cp = getCurrentComponent();
8343                     if (cp != null) {
8344                         cp.setForeground(c);
8345                     }
8346                 }
8347             }
8348 
8349             /**
8350              * Gets the <code>Cursor</code> of this object.
8351              *
8352              * @return the <code>Cursor</code>, if supported,
8353              *    of the object; otherwise, <code>null</code>
8354              */
8355             public Cursor getCursor() {
8356                 AccessibleContext ac = getCurrentAccessibleContext();
8357                 if (ac instanceof AccessibleComponent) {
8358                     return ((AccessibleComponent) ac).getCursor();
8359                 } else {
8360                     Component c = getCurrentComponent();
8361                     if (c != null) {
8362                         return c.getCursor();
8363                     } else {
8364                         Accessible ap = getAccessibleParent();
8365                         if (ap instanceof AccessibleComponent) {
8366                             return ((AccessibleComponent) ap).getCursor();
8367                         } else {
8368                             return null;
8369                         }
8370                     }
8371                 }
8372             }
8373 
8374             /**
8375              * Sets the <code>Cursor</code> of this object.
8376              *
8377              * @param c the new <code>Cursor</code> for the object
8378              */
8379             public void setCursor(Cursor c) {
8380                 AccessibleContext ac = getCurrentAccessibleContext();
8381                 if (ac instanceof AccessibleComponent) {
8382                     ((AccessibleComponent) ac).setCursor(c);
8383                 } else {
8384                     Component cp = getCurrentComponent();
8385                     if (cp != null) {
8386                         cp.setCursor(c);
8387                     }
8388                 }
8389             }
8390 
8391             /**
8392              * Gets the <code>Font</code> of this object.
8393              *
8394              * @return the <code>Font</code>,if supported,
8395              *   for the object; otherwise, <code>null</code>
8396              */
8397             public Font getFont() {
8398                 AccessibleContext ac = getCurrentAccessibleContext();
8399                 if (ac instanceof AccessibleComponent) {
8400                     return ((AccessibleComponent) ac).getFont();
8401                 } else {
8402                     Component c = getCurrentComponent();
8403                     if (c != null) {
8404                         return c.getFont();
8405                     } else {
8406                         return null;
8407                     }
8408                 }
8409             }
8410 
8411             /**
8412              * Sets the <code>Font</code> of this object.
8413              *
8414              * @param f the new <code>Font</code> for the object
8415              */
8416             public void setFont(Font f) {
8417                 AccessibleContext ac = getCurrentAccessibleContext();
8418                 if (ac instanceof AccessibleComponent) {
8419                     ((AccessibleComponent) ac).setFont(f);
8420                 } else {
8421                     Component c = getCurrentComponent();
8422                     if (c != null) {
8423                         c.setFont(f);
8424                     }
8425                 }
8426             }
8427 
8428             /**
8429              * Gets the <code>FontMetrics</code> of this object.
8430              *
8431              * @param f the <code>Font</code>
8432              * @return the <code>FontMetrics</code> object, if supported;
8433              *    otherwise <code>null</code>
8434              * @see #getFont
8435              */
8436             public FontMetrics getFontMetrics(Font f) {
8437                 AccessibleContext ac = getCurrentAccessibleContext();
8438                 if (ac instanceof AccessibleComponent) {
8439                     return ((AccessibleComponent) ac).getFontMetrics(f);
8440                 } else {
8441                     Component c = getCurrentComponent();
8442                     if (c != null) {
8443                         return c.getFontMetrics(f);
8444                     } else {
8445                         return null;
8446                     }
8447                 }
8448             }
8449 
8450             /**
8451              * Determines if the object is enabled.
8452              *
8453              * @return true if object is enabled; otherwise, false
8454              */
8455             public boolean isEnabled() {
8456                 AccessibleContext ac = getCurrentAccessibleContext();
8457                 if (ac instanceof AccessibleComponent) {
8458                     return ((AccessibleComponent) ac).isEnabled();
8459                 } else {
8460                     Component c = getCurrentComponent();
8461                     if (c != null) {
8462                         return c.isEnabled();
8463                     } else {
8464                         return false;
8465                     }
8466                 }
8467             }
8468 
8469             /**
8470              * Sets the enabled state of the object.
8471              *
8472              * @param b if true, enables this object; otherwise, disables it
8473              */
8474             public void setEnabled(boolean b) {
8475                 AccessibleContext ac = getCurrentAccessibleContext();
8476                 if (ac instanceof AccessibleComponent) {
8477                     ((AccessibleComponent) ac).setEnabled(b);
8478                 } else {
8479                     Component c = getCurrentComponent();
8480                     if (c != null) {
8481                         c.setEnabled(b);
8482                     }
8483                 }
8484             }
8485 
8486             /**
8487              * Determines if this object is visible.  Note: this means that the
8488              * object intends to be visible; however, it may not in fact be
8489              * showing on the screen because one of the objects that this object
8490              * is contained by is not visible.  To determine if an object is
8491              * showing on the screen, use <code>isShowing</code>.
8492              *
8493              * @return true if object is visible; otherwise, false
8494              */
8495             public boolean isVisible() {
8496                 AccessibleContext ac = getCurrentAccessibleContext();
8497                 if (ac instanceof AccessibleComponent) {
8498                     return ((AccessibleComponent) ac).isVisible();
8499                 } else {
8500                     Component c = getCurrentComponent();
8501                     if (c != null) {
8502                         return c.isVisible();
8503                     } else {
8504                         return false;
8505                     }
8506                 }
8507             }
8508 
8509             /**
8510              * Sets the visible state of the object.
8511              *
8512              * @param b if true, shows this object; otherwise, hides it
8513              */
8514             public void setVisible(boolean b) {
8515                 AccessibleContext ac = getCurrentAccessibleContext();
8516                 if (ac instanceof AccessibleComponent) {
8517                     ((AccessibleComponent) ac).setVisible(b);
8518                 } else {
8519                     Component c = getCurrentComponent();
8520                     if (c != null) {
8521                         c.setVisible(b);
8522                     }
8523                 }
8524             }
8525 
8526             /**
8527              * Determines if the object is showing.  This is determined
8528              * by checking the visibility of the object and ancestors
8529              * of the object.  Note: this will return true even if the
8530              * object is obscured by another (for example,
8531              * it happens to be underneath a menu that was pulled down).
8532              *
8533              * @return true if the object is showing; otherwise, false
8534              */
8535             public boolean isShowing() {
8536                 AccessibleContext ac = getCurrentAccessibleContext();
8537                 if (ac instanceof AccessibleComponent) {
8538                     if (ac.getAccessibleParent() != null) {
8539                         return ((AccessibleComponent) ac).isShowing();
8540                     } else {
8541                         // Fixes 4529616 - AccessibleJTableCell.isShowing()
8542                         // returns false when the cell on the screen
8543                         // if no parent
8544                         return isVisible();
8545                     }
8546                 } else {
8547                     Component c = getCurrentComponent();
8548                     if (c != null) {
8549                         return c.isShowing();
8550                     } else {
8551                         return false;
8552                     }
8553                 }
8554             }
8555 
8556             /**
8557              * Checks whether the specified point is within this
8558              * object's bounds, where the point's x and y coordinates
8559              * are defined to be relative to the coordinate system of
8560              * the object.
8561              *
8562              * @param p the <code>Point</code> relative to the
8563              *    coordinate system of the object
8564              * @return true if object contains <code>Point</code>;
8565              *    otherwise false
8566              */
8567             public boolean contains(Point p) {
8568                 AccessibleContext ac = getCurrentAccessibleContext();
8569                 if (ac instanceof AccessibleComponent) {
8570                     Rectangle r = ((AccessibleComponent) ac).getBounds();
8571                     return r.contains(p);
8572                 } else {
8573                     Component c = getCurrentComponent();
8574                     if (c != null) {
8575                         Rectangle r = c.getBounds();
8576                         return r.contains(p);
8577                     } else {
8578                         return getBounds().contains(p);
8579                     }
8580                 }
8581             }
8582 
8583             /**
8584              * Returns the location of the object on the screen.
8585              *
8586              * @return location of object on screen -- can be
8587              *    <code>null</code> if this object is not on the screen
8588              */
8589             public Point getLocationOnScreen() {
8590                 if (parent != null && parent.isShowing()) {
8591                     Point parentLocation = parent.getLocationOnScreen();
8592                     Point componentLocation = getLocation();
8593                     componentLocation.translate(parentLocation.x, parentLocation.y);
8594                     return componentLocation;
8595                 } else {
8596                     return null;
8597                 }
8598             }
8599 
8600             /**
8601              * Gets the location of the object relative to the parent
8602              * in the form of a point specifying the object's
8603              * top-left corner in the screen's coordinate space.
8604              *
8605              * @return an instance of <code>Point</code> representing
8606              *    the top-left corner of the object's bounds in the
8607              *    coordinate space of the screen; <code>null</code> if
8608              *    this object or its parent are not on the screen
8609              */
8610             public Point getLocation() {
8611                 if (parent != null) {
8612                     Rectangle r = parent.getCellRect(row, column, false);
8613                     if (r != null) {
8614                         return r.getLocation();
8615                     }
8616                 }
8617                 return null;
8618             }
8619 
8620             /**
8621              * Sets the location of the object relative to the parent.
8622              */
8623             public void setLocation(Point p) {
8624 //              if ((parent != null)  && (parent.contains(p))) {
8625 //                  ensureIndexIsVisible(indexInParent);
8626 //              }
8627             }
8628 
8629             public Rectangle getBounds() {
8630                 if (parent != null) {
8631                     return parent.getCellRect(row, column, false);
8632                 } else {
8633                     return null;
8634                 }
8635             }
8636 
8637             public void setBounds(Rectangle r) {
8638                 AccessibleContext ac = getCurrentAccessibleContext();
8639                 if (ac instanceof AccessibleComponent) {
8640                     ((AccessibleComponent) ac).setBounds(r);
8641                 } else {
8642                     Component c = getCurrentComponent();
8643                     if (c != null) {
8644                         c.setBounds(r);
8645                     }
8646                 }
8647             }
8648 
8649             public Dimension getSize() {
8650                 if (parent != null) {
8651                     Rectangle r = parent.getCellRect(row, column, false);
8652                     if (r != null) {
8653                         return r.getSize();
8654                     }
8655                 }
8656                 return null;
8657             }
8658 
8659             public void setSize (Dimension d) {
8660                 AccessibleContext ac = getCurrentAccessibleContext();
8661                 if (ac instanceof AccessibleComponent) {
8662                     ((AccessibleComponent) ac).setSize(d);
8663                 } else {
8664                     Component c = getCurrentComponent();
8665                     if (c != null) {
8666                         c.setSize(d);
8667                     }
8668                 }
8669             }
8670 
8671             public Accessible getAccessibleAt(Point p) {
8672                 AccessibleContext ac = getCurrentAccessibleContext();
8673                 if (ac instanceof AccessibleComponent) {
8674                     return ((AccessibleComponent) ac).getAccessibleAt(p);
8675                 } else {
8676                     return null;
8677                 }
8678             }
8679 
8680             public boolean isFocusTraversable() {
8681                 AccessibleContext ac = getCurrentAccessibleContext();
8682                 if (ac instanceof AccessibleComponent) {
8683                     return ((AccessibleComponent) ac).isFocusTraversable();
8684                 } else {
8685                     Component c = getCurrentComponent();
8686                     if (c != null) {
8687                         return c.isFocusTraversable();
8688                     } else {
8689                         return false;
8690                     }
8691                 }
8692             }
8693 
8694             public void requestFocus() {
8695                 AccessibleContext ac = getCurrentAccessibleContext();
8696                 if (ac instanceof AccessibleComponent) {
8697                     ((AccessibleComponent) ac).requestFocus();
8698                 } else {
8699                     Component c = getCurrentComponent();
8700                     if (c != null) {
8701                         c.requestFocus();
8702                     }
8703                 }
8704             }
8705 
8706             public void addFocusListener(FocusListener l) {
8707                 AccessibleContext ac = getCurrentAccessibleContext();
8708                 if (ac instanceof AccessibleComponent) {
8709                     ((AccessibleComponent) ac).addFocusListener(l);
8710                 } else {
8711                     Component c = getCurrentComponent();
8712                     if (c != null) {
8713                         c.addFocusListener(l);
8714                     }
8715                 }
8716             }
8717 
8718             public void removeFocusListener(FocusListener l) {
8719                 AccessibleContext ac = getCurrentAccessibleContext();
8720                 if (ac instanceof AccessibleComponent) {
8721                     ((AccessibleComponent) ac).removeFocusListener(l);
8722                 } else {
8723                     Component c = getCurrentComponent();
8724                     if (c != null) {
8725                         c.removeFocusListener(l);
8726                     }
8727                 }
8728             }
8729 
8730         } // inner class AccessibleJTableCell
8731 
8732         // Begin AccessibleJTableHeader ========== // TIGER - 4715503
8733 
8734         /**
8735          * This class implements accessibility for JTable header cells.
8736          */
8737         private class AccessibleJTableHeaderCell extends AccessibleContext
8738             implements Accessible, AccessibleComponent {
8739 
8740             private int row;
8741             private int column;
8742             private JTableHeader parent;
8743             private Component rendererComponent;
8744 
8745             /**
8746              * Constructs an <code>AccessibleJTableHeaderEntry</code> instance.
8747              *
8748              * @param row header cell row index
8749              * @param column header cell column index
8750              * @param parent header cell parent
8751              * @param rendererComponent component that renders the header cell
8752              */
8753             public AccessibleJTableHeaderCell(int row, int column,
8754                                               JTableHeader parent,
8755                                               Component rendererComponent) {
8756                 this.row = row;
8757                 this.column = column;
8758                 this.parent = parent;
8759                 this.rendererComponent = rendererComponent;
8760                 this.setAccessibleParent(parent);
8761             }
8762 
8763             /**
8764              * Gets the <code>AccessibleContext</code> associated with this
8765              * component. In the implementation of the Java Accessibility
8766              * API for this class, return this object, which is its own
8767              * <code>AccessibleContext</code>.
8768              *
8769              * @return this object
8770              */
8771             public AccessibleContext getAccessibleContext() {
8772                 return this;
8773             }
8774 
8775             /*
8776              * Returns the AccessibleContext for the header cell
8777              * renderer.
8778              */
8779             private AccessibleContext getCurrentAccessibleContext() {
8780                 return rendererComponent.getAccessibleContext();
8781             }
8782 
8783             /*
8784              * Returns the component that renders the header cell.
8785              */
8786             private Component getCurrentComponent() {
8787                 return rendererComponent;
8788             }
8789 
8790             // AccessibleContext methods ==========
8791 
8792             /**
8793              * Gets the accessible name of this object.
8794              *
8795              * @return the localized name of the object; <code>null</code>
8796              *     if this object does not have a name
8797              */
8798             public String getAccessibleName() {
8799                 AccessibleContext ac = getCurrentAccessibleContext();
8800                 if (ac != null) {
8801                     String name = ac.getAccessibleName();
8802                     if ((name != null) && (name != "")) {
8803                         return ac.getAccessibleName();
8804                     }
8805                 }
8806                 if ((accessibleName != null) && (accessibleName != "")) {
8807                     return accessibleName;
8808                 } else {
8809                     return null;
8810                 }
8811             }
8812 
8813             /**
8814              * Sets the localized accessible name of this object.
8815              *
8816              * @param s the new localized name of the object
8817              */
8818             public void setAccessibleName(String s) {
8819                 AccessibleContext ac = getCurrentAccessibleContext();
8820                 if (ac != null) {
8821                     ac.setAccessibleName(s);
8822                 } else {
8823                     super.setAccessibleName(s);
8824                 }
8825             }
8826 
8827             /**
8828              * Gets the accessible description of this object.
8829              *
8830              * @return the localized description of the object;
8831              *     <code>null</code> if this object does not have
8832              *     a description
8833              */
8834             public String getAccessibleDescription() {
8835                 AccessibleContext ac = getCurrentAccessibleContext();
8836                 if (ac != null) {
8837                     return ac.getAccessibleDescription();
8838                 } else {
8839                     return super.getAccessibleDescription();
8840                 }
8841             }
8842 
8843             /**
8844              * Sets the accessible description of this object.
8845              *
8846              * @param s the new localized description of the object
8847              */
8848             public void setAccessibleDescription(String s) {
8849                 AccessibleContext ac = getCurrentAccessibleContext();
8850                 if (ac != null) {
8851                     ac.setAccessibleDescription(s);
8852                 } else {
8853                     super.setAccessibleDescription(s);
8854                 }
8855             }
8856 
8857             /**
8858              * Gets the role of this object.
8859              *
8860              * @return an instance of <code>AccessibleRole</code>
8861              *      describing the role of the object
8862              * @see AccessibleRole
8863              */
8864             public AccessibleRole getAccessibleRole() {
8865                 AccessibleContext ac = getCurrentAccessibleContext();
8866                 if (ac != null) {
8867                     return ac.getAccessibleRole();
8868                 } else {
8869                     return AccessibleRole.UNKNOWN;
8870                 }
8871             }
8872 
8873             /**
8874              * Gets the state set of this object.
8875              *
8876              * @return an instance of <code>AccessibleStateSet</code>
8877              *     containing the current state set of the object
8878              * @see AccessibleState
8879              */
8880             public AccessibleStateSet getAccessibleStateSet() {
8881                 AccessibleContext ac = getCurrentAccessibleContext();
8882                 AccessibleStateSet as = null;
8883 
8884                 if (ac != null) {
8885                     as = ac.getAccessibleStateSet();
8886                 }
8887                 if (as == null) {
8888                     as = new AccessibleStateSet();
8889                 }
8890                 Rectangle rjt = JTable.this.getVisibleRect();
8891                 Rectangle rcell = JTable.this.getCellRect(row, column, false);
8892                 if (rjt.intersects(rcell)) {
8893                     as.add(AccessibleState.SHOWING);
8894                 } else {
8895                     if (as.contains(AccessibleState.SHOWING)) {
8896                          as.remove(AccessibleState.SHOWING);
8897                     }
8898                 }
8899                 if (JTable.this.isCellSelected(row, column)) {
8900                     as.add(AccessibleState.SELECTED);
8901                 } else if (as.contains(AccessibleState.SELECTED)) {
8902                     as.remove(AccessibleState.SELECTED);
8903                 }
8904                 if ((row == getSelectedRow()) && (column == getSelectedColumn())) {
8905                     as.add(AccessibleState.ACTIVE);
8906                 }
8907                 as.add(AccessibleState.TRANSIENT);
8908                 return as;
8909             }
8910 
8911             /**
8912              * Gets the <code>Accessible</code> parent of this object.
8913              *
8914              * @return the Accessible parent of this object;
8915              *     <code>null</code> if this object does not
8916              *     have an <code>Accessible</code> parent
8917              */
8918             public Accessible getAccessibleParent() {
8919                 return parent;
8920             }
8921 
8922             /**
8923              * Gets the index of this object in its accessible parent.
8924              *
8925              * @return the index of this object in its parent; -1 if this
8926              *     object does not have an accessible parent
8927              * @see #getAccessibleParent
8928              */
8929             public int getAccessibleIndexInParent() {
8930                 return column;
8931             }
8932 
8933             /**
8934              * Returns the number of accessible children in the object.
8935              *
8936              * @return the number of accessible children in the object
8937              */
8938             public int getAccessibleChildrenCount() {
8939                 AccessibleContext ac = getCurrentAccessibleContext();
8940                 if (ac != null) {
8941                     return ac.getAccessibleChildrenCount();
8942                 } else {
8943                     return 0;
8944                 }
8945             }
8946 
8947             /**
8948              * Returns the specified <code>Accessible</code> child of the
8949              * object.
8950              *
8951              * @param i zero-based index of child
8952              * @return the <code>Accessible</code> child of the object
8953              */
8954             public Accessible getAccessibleChild(int i) {
8955                 AccessibleContext ac = getCurrentAccessibleContext();
8956                 if (ac != null) {
8957                     Accessible accessibleChild = ac.getAccessibleChild(i);
8958                     ac.setAccessibleParent(this);
8959                     return accessibleChild;
8960                 } else {
8961                     return null;
8962                 }
8963             }
8964 
8965             /**
8966              * Gets the locale of the component. If the component
8967              * does not have a locale, then the locale of its parent
8968              * is returned.
8969              *
8970              * @return this component's locale; if this component does
8971              *    not have a locale, the locale of its parent is returned
8972              * @exception IllegalComponentStateException if the
8973              *    <code>Component</code> does not have its own locale
8974              *    and has not yet been added to a containment hierarchy
8975              *    such that the locale can be determined from the
8976              *    containing parent
8977              * @see #setLocale
8978              */
8979             public Locale getLocale() {
8980                 AccessibleContext ac = getCurrentAccessibleContext();
8981                 if (ac != null) {
8982                     return ac.getLocale();
8983                 } else {
8984                     return null;
8985                 }
8986             }
8987 
8988             /**
8989              * Adds a <code>PropertyChangeListener</code> to the listener list.
8990              * The listener is registered for all properties.
8991              *
8992              * @param l  the <code>PropertyChangeListener</code>
8993              *     to be added
8994              */
8995             public void addPropertyChangeListener(PropertyChangeListener l) {
8996                 AccessibleContext ac = getCurrentAccessibleContext();
8997                 if (ac != null) {
8998                     ac.addPropertyChangeListener(l);
8999                 } else {
9000                     super.addPropertyChangeListener(l);
9001                 }
9002             }
9003 
9004             /**
9005              * Removes a <code>PropertyChangeListener</code> from the
9006              * listener list. This removes a <code>PropertyChangeListener</code>
9007              * that was registered for all properties.
9008              *
9009              * @param l  the <code>PropertyChangeListener</code>
9010              *    to be removed
9011              */
9012             public void removePropertyChangeListener(PropertyChangeListener l) {
9013                 AccessibleContext ac = getCurrentAccessibleContext();
9014                 if (ac != null) {
9015                     ac.removePropertyChangeListener(l);
9016                 } else {
9017                     super.removePropertyChangeListener(l);
9018                 }
9019             }
9020 
9021             /**
9022              * Gets the <code>AccessibleAction</code> associated with this
9023              * object if one exists.  Otherwise returns <code>null</code>.
9024              *
9025              * @return the <code>AccessibleAction</code>, or <code>null</code>
9026              */
9027             public AccessibleAction getAccessibleAction() {
9028                 return getCurrentAccessibleContext().getAccessibleAction();
9029             }
9030 
9031             /**
9032              * Gets the <code>AccessibleComponent</code> associated with
9033              * this object if one exists.  Otherwise returns <code>null</code>.
9034              *
9035              * @return the <code>AccessibleComponent</code>, or
9036              *    <code>null</code>
9037              */
9038             public AccessibleComponent getAccessibleComponent() {
9039                 return this; // to override getBounds()
9040             }
9041 
9042             /**
9043              * Gets the <code>AccessibleSelection</code> associated with
9044              * this object if one exists.  Otherwise returns <code>null</code>.
9045              *
9046              * @return the <code>AccessibleSelection</code>, or
9047              *    <code>null</code>
9048              */
9049             public AccessibleSelection getAccessibleSelection() {
9050                 return getCurrentAccessibleContext().getAccessibleSelection();
9051             }
9052 
9053             /**
9054              * Gets the <code>AccessibleText</code> associated with this
9055              * object if one exists.  Otherwise returns <code>null</code>.
9056              *
9057              * @return the <code>AccessibleText</code>, or <code>null</code>
9058              */
9059             public AccessibleText getAccessibleText() {
9060                 return getCurrentAccessibleContext().getAccessibleText();
9061             }
9062 
9063             /**
9064              * Gets the <code>AccessibleValue</code> associated with
9065              * this object if one exists.  Otherwise returns <code>null</code>.
9066              *
9067              * @return the <code>AccessibleValue</code>, or <code>null</code>
9068              */
9069             public AccessibleValue getAccessibleValue() {
9070                 return getCurrentAccessibleContext().getAccessibleValue();
9071             }
9072 
9073 
9074             // AccessibleComponent methods ==========
9075 
9076             /**
9077              * Gets the background color of this object.
9078              *
9079              * @return the background color, if supported, of the object;
9080              *     otherwise, <code>null</code>
9081              */
9082             public Color getBackground() {
9083                 AccessibleContext ac = getCurrentAccessibleContext();
9084                 if (ac instanceof AccessibleComponent) {
9085                     return ((AccessibleComponent) ac).getBackground();
9086                 } else {
9087                     Component c = getCurrentComponent();
9088                     if (c != null) {
9089                         return c.getBackground();
9090                     } else {
9091                         return null;
9092                     }
9093                 }
9094             }
9095 
9096             /**
9097              * Sets the background color of this object.
9098              *
9099              * @param c the new <code>Color</code> for the background
9100              */
9101             public void setBackground(Color c) {
9102                 AccessibleContext ac = getCurrentAccessibleContext();
9103                 if (ac instanceof AccessibleComponent) {
9104                     ((AccessibleComponent) ac).setBackground(c);
9105                 } else {
9106                     Component cp = getCurrentComponent();
9107                     if (cp != null) {
9108                         cp.setBackground(c);
9109                     }
9110                 }
9111             }
9112 
9113             /**
9114              * Gets the foreground color of this object.
9115              *
9116              * @return the foreground color, if supported, of the object;
9117              *     otherwise, <code>null</code>
9118              */
9119             public Color getForeground() {
9120                 AccessibleContext ac = getCurrentAccessibleContext();
9121                 if (ac instanceof AccessibleComponent) {
9122                     return ((AccessibleComponent) ac).getForeground();
9123                 } else {
9124                     Component c = getCurrentComponent();
9125                     if (c != null) {
9126                         return c.getForeground();
9127                     } else {
9128                         return null;
9129                     }
9130                 }
9131             }
9132 
9133             /**
9134              * Sets the foreground color of this object.
9135              *
9136              * @param c the new <code>Color</code> for the foreground
9137              */
9138             public void setForeground(Color c) {
9139                 AccessibleContext ac = getCurrentAccessibleContext();
9140                 if (ac instanceof AccessibleComponent) {
9141                     ((AccessibleComponent) ac).setForeground(c);
9142                 } else {
9143                     Component cp = getCurrentComponent();
9144                     if (cp != null) {
9145                         cp.setForeground(c);
9146                     }
9147                 }
9148             }
9149 
9150             /**
9151              * Gets the <code>Cursor</code> of this object.
9152              *
9153              * @return the <code>Cursor</code>, if supported,
9154              *    of the object; otherwise, <code>null</code>
9155              */
9156             public Cursor getCursor() {
9157                 AccessibleContext ac = getCurrentAccessibleContext();
9158                 if (ac instanceof AccessibleComponent) {
9159                     return ((AccessibleComponent) ac).getCursor();
9160                 } else {
9161                     Component c = getCurrentComponent();
9162                     if (c != null) {
9163                         return c.getCursor();
9164                     } else {
9165                         Accessible ap = getAccessibleParent();
9166                         if (ap instanceof AccessibleComponent) {
9167                             return ((AccessibleComponent) ap).getCursor();
9168                         } else {
9169                             return null;
9170                         }
9171                     }
9172                 }
9173             }
9174 
9175             /**
9176              * Sets the <code>Cursor</code> of this object.
9177              *
9178              * @param c the new <code>Cursor</code> for the object
9179              */
9180             public void setCursor(Cursor c) {
9181                 AccessibleContext ac = getCurrentAccessibleContext();
9182                 if (ac instanceof AccessibleComponent) {
9183                     ((AccessibleComponent) ac).setCursor(c);
9184                 } else {
9185                     Component cp = getCurrentComponent();
9186                     if (cp != null) {
9187                         cp.setCursor(c);
9188                     }
9189                 }
9190             }
9191 
9192             /**
9193              * Gets the <code>Font</code> of this object.
9194              *
9195              * @return the <code>Font</code>,if supported,
9196              *   for the object; otherwise, <code>null</code>
9197              */
9198             public Font getFont() {
9199                 AccessibleContext ac = getCurrentAccessibleContext();
9200                 if (ac instanceof AccessibleComponent) {
9201                     return ((AccessibleComponent) ac).getFont();
9202                 } else {
9203                     Component c = getCurrentComponent();
9204                     if (c != null) {
9205                         return c.getFont();
9206                     } else {
9207                         return null;
9208                     }
9209                 }
9210             }
9211 
9212             /**
9213              * Sets the <code>Font</code> of this object.
9214              *
9215              * @param f the new <code>Font</code> for the object
9216              */
9217             public void setFont(Font f) {
9218                 AccessibleContext ac = getCurrentAccessibleContext();
9219                 if (ac instanceof AccessibleComponent) {
9220                     ((AccessibleComponent) ac).setFont(f);
9221                 } else {
9222                     Component c = getCurrentComponent();
9223                     if (c != null) {
9224                         c.setFont(f);
9225                     }
9226                 }
9227             }
9228 
9229             /**
9230              * Gets the <code>FontMetrics</code> of this object.
9231              *
9232              * @param f the <code>Font</code>
9233              * @return the <code>FontMetrics</code> object, if supported;
9234              *    otherwise <code>null</code>
9235              * @see #getFont
9236              */
9237             public FontMetrics getFontMetrics(Font f) {
9238                 AccessibleContext ac = getCurrentAccessibleContext();
9239                 if (ac instanceof AccessibleComponent) {
9240                     return ((AccessibleComponent) ac).getFontMetrics(f);
9241                 } else {
9242                     Component c = getCurrentComponent();
9243                     if (c != null) {
9244                         return c.getFontMetrics(f);
9245                     } else {
9246                         return null;
9247                     }
9248                 }
9249             }
9250 
9251             /**
9252              * Determines if the object is enabled.
9253              *
9254              * @return true if object is enabled; otherwise, false
9255              */
9256             public boolean isEnabled() {
9257                 AccessibleContext ac = getCurrentAccessibleContext();
9258                 if (ac instanceof AccessibleComponent) {
9259                     return ((AccessibleComponent) ac).isEnabled();
9260                 } else {
9261                     Component c = getCurrentComponent();
9262                     if (c != null) {
9263                         return c.isEnabled();
9264                     } else {
9265                         return false;
9266                     }
9267                 }
9268             }
9269 
9270             /**
9271              * Sets the enabled state of the object.
9272              *
9273              * @param b if true, enables this object; otherwise, disables it
9274              */
9275             public void setEnabled(boolean b) {
9276                 AccessibleContext ac = getCurrentAccessibleContext();
9277                 if (ac instanceof AccessibleComponent) {
9278                     ((AccessibleComponent) ac).setEnabled(b);
9279                 } else {
9280                     Component c = getCurrentComponent();
9281                     if (c != null) {
9282                         c.setEnabled(b);
9283                     }
9284                 }
9285             }
9286 
9287             /**
9288              * Determines if this object is visible.  Note: this means that the
9289              * object intends to be visible; however, it may not in fact be
9290              * showing on the screen because one of the objects that this object
9291              * is contained by is not visible.  To determine if an object is
9292              * showing on the screen, use <code>isShowing</code>.
9293              *
9294              * @return true if object is visible; otherwise, false
9295              */
9296             public boolean isVisible() {
9297                 AccessibleContext ac = getCurrentAccessibleContext();
9298                 if (ac instanceof AccessibleComponent) {
9299                     return ((AccessibleComponent) ac).isVisible();
9300                 } else {
9301                     Component c = getCurrentComponent();
9302                     if (c != null) {
9303                         return c.isVisible();
9304                     } else {
9305                         return false;
9306                     }
9307                 }
9308             }
9309 
9310             /**
9311              * Sets the visible state of the object.
9312              *
9313              * @param b if true, shows this object; otherwise, hides it
9314              */
9315             public void setVisible(boolean b) {
9316                 AccessibleContext ac = getCurrentAccessibleContext();
9317                 if (ac instanceof AccessibleComponent) {
9318                     ((AccessibleComponent) ac).setVisible(b);
9319                 } else {
9320                     Component c = getCurrentComponent();
9321                     if (c != null) {
9322                         c.setVisible(b);
9323                     }
9324                 }
9325             }
9326 
9327             /**
9328              * Determines if the object is showing.  This is determined
9329              * by checking the visibility of the object and ancestors
9330              * of the object.  Note: this will return true even if the
9331              * object is obscured by another (for example,
9332              * it happens to be underneath a menu that was pulled down).
9333              *
9334              * @return true if the object is showing; otherwise, false
9335              */
9336             public boolean isShowing() {
9337                 AccessibleContext ac = getCurrentAccessibleContext();
9338                 if (ac instanceof AccessibleComponent) {
9339                     if (ac.getAccessibleParent() != null) {
9340                         return ((AccessibleComponent) ac).isShowing();
9341                     } else {
9342                         // Fixes 4529616 - AccessibleJTableCell.isShowing()
9343                         // returns false when the cell on the screen
9344                         // if no parent
9345                         return isVisible();
9346                     }
9347                 } else {
9348                     Component c = getCurrentComponent();
9349                     if (c != null) {
9350                         return c.isShowing();
9351                     } else {
9352                         return false;
9353                     }
9354                 }
9355             }
9356 
9357             /**
9358              * Checks whether the specified point is within this
9359              * object's bounds, where the point's x and y coordinates
9360              * are defined to be relative to the coordinate system of
9361              * the object.
9362              *
9363              * @param p the <code>Point</code> relative to the
9364              *    coordinate system of the object
9365              * @return true if object contains <code>Point</code>;
9366              *    otherwise false
9367              */
9368             public boolean contains(Point p) {
9369                 AccessibleContext ac = getCurrentAccessibleContext();
9370                 if (ac instanceof AccessibleComponent) {
9371                     Rectangle r = ((AccessibleComponent) ac).getBounds();
9372                     return r.contains(p);
9373                 } else {
9374                     Component c = getCurrentComponent();
9375                     if (c != null) {
9376                         Rectangle r = c.getBounds();
9377                         return r.contains(p);
9378                     } else {
9379                         return getBounds().contains(p);
9380                     }
9381                 }
9382             }
9383 
9384             /**
9385              * Returns the location of the object on the screen.
9386              *
9387              * @return location of object on screen -- can be
9388              *    <code>null</code> if this object is not on the screen
9389              */
9390             public Point getLocationOnScreen() {
9391                 if (parent != null && parent.isShowing()) {
9392                     Point parentLocation = parent.getLocationOnScreen();
9393                     Point componentLocation = getLocation();
9394                     componentLocation.translate(parentLocation.x, parentLocation.y);
9395                     return componentLocation;
9396                 } else {
9397                     return null;
9398                 }
9399             }
9400 
9401             /**
9402              * Gets the location of the object relative to the parent
9403              * in the form of a point specifying the object's
9404              * top-left corner in the screen's coordinate space.
9405              *
9406              * @return an instance of <code>Point</code> representing
9407              *    the top-left corner of the object's bounds in the
9408              *    coordinate space of the screen; <code>null</code> if
9409              *    this object or its parent are not on the screen
9410              */
9411             public Point getLocation() {
9412                 if (parent != null) {
9413                     Rectangle r = parent.getHeaderRect(column);
9414                     if (r != null) {
9415                         return r.getLocation();
9416                     }
9417                 }
9418                 return null;
9419             }
9420 
9421             /**
9422              * Sets the location of the object relative to the parent.
9423              * @param p the new position for the top-left corner
9424              * @see #getLocation
9425              */
9426             public void setLocation(Point p) {
9427             }
9428 
9429             /**
9430              * Gets the bounds of this object in the form of a Rectangle object.
9431              * The bounds specify this object's width, height, and location
9432              * relative to its parent.
9433              *
9434              * @return A rectangle indicating this component's bounds; null if
9435              * this object is not on the screen.
9436              * @see #contains
9437              */
9438             public Rectangle getBounds() {
9439                 if (parent != null) {
9440                     return parent.getHeaderRect(column);
9441                 } else {
9442                     return null;
9443                 }
9444             }
9445 
9446             /**
9447              * Sets the bounds of this object in the form of a Rectangle object.
9448              * The bounds specify this object's width, height, and location
9449              * relative to its parent.
9450              *
9451              * @param r rectangle indicating this component's bounds
9452              * @see #getBounds
9453              */
9454             public void setBounds(Rectangle r) {
9455                 AccessibleContext ac = getCurrentAccessibleContext();
9456                 if (ac instanceof AccessibleComponent) {
9457                     ((AccessibleComponent) ac).setBounds(r);
9458                 } else {
9459                     Component c = getCurrentComponent();
9460                     if (c != null) {
9461                         c.setBounds(r);
9462                     }
9463                 }
9464             }
9465 
9466             /**
9467              * Returns the size of this object in the form of a Dimension object.
9468              * The height field of the Dimension object contains this object's
9469              * height, and the width field of the Dimension object contains this
9470              * object's width.
9471              *
9472              * @return A Dimension object that indicates the size of this component;
9473              * null if this object is not on the screen
9474              * @see #setSize
9475              */
9476             public Dimension getSize() {
9477                 if (parent != null) {
9478                     Rectangle r = parent.getHeaderRect(column);
9479                     if (r != null) {
9480                         return r.getSize();
9481                     }
9482                 }
9483                 return null;
9484             }
9485 
9486             /**
9487              * Resizes this object so that it has width and height.
9488              *
9489              * @param d The dimension specifying the new size of the object.
9490              * @see #getSize
9491              */
9492             public void setSize (Dimension d) {
9493                 AccessibleContext ac = getCurrentAccessibleContext();
9494                 if (ac instanceof AccessibleComponent) {
9495                     ((AccessibleComponent) ac).setSize(d);
9496                 } else {
9497                     Component c = getCurrentComponent();
9498                     if (c != null) {
9499                         c.setSize(d);
9500                     }
9501                 }
9502             }
9503 
9504             /**
9505              * Returns the Accessible child, if one exists, contained at the local
9506              * coordinate Point.
9507              *
9508              * @param p The point relative to the coordinate system of this object.
9509              * @return the Accessible, if it exists, at the specified location;
9510              * otherwise null
9511              */
9512             public Accessible getAccessibleAt(Point p) {
9513                 AccessibleContext ac = getCurrentAccessibleContext();
9514                 if (ac instanceof AccessibleComponent) {
9515                     return ((AccessibleComponent) ac).getAccessibleAt(p);
9516                 } else {
9517                     return null;
9518                 }
9519             }
9520 
9521             /**
9522              * Returns whether this object can accept focus or not.   Objects that
9523              * can accept focus will also have the AccessibleState.FOCUSABLE state
9524              * set in their AccessibleStateSets.
9525              *
9526              * @return true if object can accept focus; otherwise false
9527              * @see AccessibleContext#getAccessibleStateSet
9528              * @see AccessibleState#FOCUSABLE
9529              * @see AccessibleState#FOCUSED
9530              * @see AccessibleStateSet
9531              */
9532             public boolean isFocusTraversable() {
9533                 AccessibleContext ac = getCurrentAccessibleContext();
9534                 if (ac instanceof AccessibleComponent) {
9535                     return ((AccessibleComponent) ac).isFocusTraversable();
9536                 } else {
9537                     Component c = getCurrentComponent();
9538                     if (c != null) {
9539                         return c.isFocusTraversable();
9540                     } else {
9541                         return false;
9542                     }
9543                 }
9544             }
9545 
9546             /**
9547              * Requests focus for this object.  If this object cannot accept focus,
9548              * nothing will happen.  Otherwise, the object will attempt to take
9549              * focus.
9550              * @see #isFocusTraversable
9551              */
9552             public void requestFocus() {
9553                 AccessibleContext ac = getCurrentAccessibleContext();
9554                 if (ac instanceof AccessibleComponent) {
9555                     ((AccessibleComponent) ac).requestFocus();
9556                 } else {
9557                     Component c = getCurrentComponent();
9558                     if (c != null) {
9559                         c.requestFocus();
9560                     }
9561                 }
9562             }
9563 
9564             /**
9565              * Adds the specified focus listener to receive focus events from this
9566              * component.
9567              *
9568              * @param l the focus listener
9569              * @see #removeFocusListener
9570              */
9571             public void addFocusListener(FocusListener l) {
9572                 AccessibleContext ac = getCurrentAccessibleContext();
9573                 if (ac instanceof AccessibleComponent) {
9574                     ((AccessibleComponent) ac).addFocusListener(l);
9575                 } else {
9576                     Component c = getCurrentComponent();
9577                     if (c != null) {
9578                         c.addFocusListener(l);
9579                     }
9580                 }
9581             }
9582 
9583             /**
9584              * Removes the specified focus listener so it no longer receives focus
9585              * events from this component.
9586              *
9587              * @param l the focus listener
9588              * @see #addFocusListener
9589              */
9590             public void removeFocusListener(FocusListener l) {
9591                 AccessibleContext ac = getCurrentAccessibleContext();
9592                 if (ac instanceof AccessibleComponent) {
9593                     ((AccessibleComponent) ac).removeFocusListener(l);
9594                 } else {
9595                     Component c = getCurrentComponent();
9596                     if (c != null) {
9597                         c.removeFocusListener(l);
9598                     }
9599                 }
9600             }
9601 
9602         } // inner class AccessibleJTableHeaderCell
9603 
9604     }  // inner class AccessibleJTable
9605 
9606 }  // End of Class JTable