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