| JavaTM 2 Platform Std. Ed. v1.6.0
javax.swing
Class JTable
java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
javax.swing.JTable
- All Implemented Interfaces:
- ImageObserver, MenuContainer, Serializable, EventListener, Accessible, CellEditorListener, ListSelectionListener, RowSorterListener, TableColumnModelListener, TableModelListener, Scrollable
public class JTable - extends JComponent
- implements TableModelListener, Scrollable, TableColumnModelListener, ListSelectionListener, CellEditorListener, Accessible, RowSorterListener
The JTable is used to display and edit regular two-dimensional tables
of cells.
See How to Use Tables
in The Java Tutorial
for task-oriented documentation and examples of using JTable.
The JTable has many
facilities that make it possible to customize its rendering and editing
but provides defaults for these features so that simple tables can be
set up easily. For example, to set up a table with 10 rows and 10
columns of numbers:
TableModel dataModel = new AbstractTableModel() {
public int getColumnCount() { return 10; }
public int getRowCount() { return 10;}
public Object getValueAt(int row, int col) { return new Integer(row*col); }
};
JTable table = new JTable(dataModel);
JScrollPane scrollpane = new JScrollPane(table);
Note that if you wish to use a JTable in a standalone
view (outside of a JScrollPane) and want the header
displayed, you can get it using getTableHeader() and
display it separately.
To enable sorting and filtering of rows, use a
RowSorter.
You can set up a row sorter in either of two ways:
- Directly set the
RowSorter. For example:
table.setRowSorter(new TableRowSorter(model)).
- Set the
autoCreateRowSorter
property to true, so that the JTable
creates a RowSorter for
you. For example: setAutoCreateRowSorter(true).
When designing applications that use the JTable it is worth paying
close attention to the data structures that will represent the table's data.
The DefaultTableModel is a model implementation that
uses a Vector of Vectors of Objects to
store the cell values. As well as copying the data from an
application into the DefaultTableModel,
it is also possible to wrap the data in the methods of the
TableModel interface so that the data can be passed to the
JTable directly, as in the example above. This often results
in more efficient applications because the model is free to choose the
internal representation that best suits the data.
A good rule of thumb for deciding whether to use the AbstractTableModel
or the DefaultTableModel is to use the AbstractTableModel
as the base class for creating subclasses and the DefaultTableModel
when subclassing is not required.
The "TableExample" directory in the demo area of the source distribution
gives a number of complete examples of JTable usage,
covering how the JTable can be used to provide an
editable view of data taken from a database and how to modify
the columns in the display to use specialized renderers and editors.
The JTable uses integers exclusively to refer to both the rows and the columns
of the model that it displays. The JTable simply takes a tabular range of cells
and uses getValueAt(int, int) to retrieve the
values from the model during painting. It is important to remember that
the column and row indexes returned by various JTable methods
are in terms of the JTable (the view) and are not
necessarily the same indexes used by the model.
By default, columns may be rearranged in the JTable so that the
view's columns appear in a different order to the columns in the model.
This does not affect the implementation of the model at all: when the
columns are reordered, the JTable maintains the new order of the columns
internally and converts its column indices before querying the model.
So, when writing a TableModel, it is not necessary to listen for column
reordering events as the model will be queried in its own coordinate
system regardless of what is happening in the view.
In the examples area there is a demonstration of a sorting algorithm making
use of exactly this technique to interpose yet another coordinate system
where the order of the rows is changed, rather than the order of the columns.
Similarly when using the sorting and filtering functionality
provided by RowSorter the underlying
TableModel does not need to know how to do sorting,
rather RowSorter will handle it. Coordinate
conversions will be necessary when using the row based methods of
JTable with the underlying TableModel.
All of JTables row based methods are in terms of the
RowSorter, which is not necessarily the same as that
of the underlying TableModel. For example, the
selection is always in terms of JTable so that when
using RowSorter you will need to convert using
convertRowIndexToView or
convertRowIndexToModel. The following shows how to
convert coordinates from JTable to that of the
underlying model:
int[] selection = table.getSelectedRows();
for (int i = 0; i < selection.length; i++) {
selection[i] = table.convertRowIndexToModel(selection[i]);
}
// selection is now in terms of the underlying TableModel
By default if sorting is enabled JTable will persist the
selection and variable row heights in terms of the model on
sorting. For example if row 0, in terms of the underlying model,
is currently selected, after the sort row 0, in terms of the
underlying model will be selected. Visually the selection may
change, but in terms of the underlying model it will remain the
same. The one exception to that is if the model index is no longer
visible or was removed. For example, if row 0 in terms of model
was filtered out the selection will be empty after the sort.
J2SE 5 adds methods to JTable to provide convenient access to some
common printing needs. Simple new print() methods allow for quick
and easy addition of printing support to your application. In addition, a new
getPrintable(javax.swing.JTable.PrintMode, java.text.MessageFormat, java.text.MessageFormat) method is available for more advanced printing needs.
As for all JComponent classes, you can use
InputMap and ActionMap to associate an
Action object with a KeyStroke and execute the
action under specified conditions.
Warning: Swing is not thread safe. For more
information see Swing's Threading
Policy.
Warning:
Serialized objects of this class will not be compatible with
future Swing releases. The current serialization support is
appropriate for short term storage or RMI between applications running
the same version of Swing. As of 1.4, support for long term storage
of all JavaBeansTM
has been added to the java.beans package.
Please see XMLEncoder.
- See Also:
DefaultTableModel,
TableRowSorter
|
Nested Class Summary |
protected class |
JTable.AccessibleJTable
This class implements accessibility support for the
JTable class. |
static class |
JTable.DropLocation
A subclass of TransferHandler.DropLocation representing
a drop location for a JTable. |
static class |
JTable.PrintMode
Printing modes, used in printing JTables. |
|
Field Summary |
static int |
AUTO_RESIZE_ALL_COLUMNS
During all resize operations, proportionately resize all columns. |
static int |
AUTO_RESIZE_LAST_COLUMN
During all resize operations, apply adjustments to the last column only. |
static int |
AUTO_RESIZE_NEXT_COLUMN
When a column is adjusted in the UI, adjust the next column the opposite way. |
static int |
AUTO_RESIZE_OFF
Do not adjust column widths automatically; use a scrollbar. |
static int |
AUTO_RESIZE_SUBSEQUENT_COLUMNS
During UI adjustment, change subsequent columns to preserve the total width;
this is the default behavior. |
protected boolean |
autoCreateColumnsFromModel
The table will query the TableModel to build the default
set of columns if this is true. |
protected int |
autoResizeMode
Determines if the table automatically resizes the
width of the table's columns to take up the entire width of the
table, and how it does the resizing. |
protected TableCellEditor |
cellEditor
The active cell editor object, that overwrites the screen real estate
occupied by the current cell and allows the user to change its contents. |
protected boolean |
cellSelectionEnabled
Obsolete as of Java 2 platform v1.3. |
protected TableColumnModel |
columnModel
The TableColumnModel of the table. |
protected TableModel |
dataModel
The TableModel of the table. |
protected Hashtable |
defaultEditorsByColumnClass
A table of objects that display and edit the contents of a cell,
indexed by class as declared in getColumnClass
in the TableModel interface. |
protected Hashtable |
defaultRenderersByColumnClass
A table of objects that display the contents of a cell,
indexed by class as declared in getColumnClass
in the TableModel interface. |
protected int |
editingColumn
Identifies the column of the cell being edited. |
protected int |
editingRow
Identifies the row of the cell being edited. |
protected Component |
editorComp
If editing, the Component that is handling the editing. |
protected Color |
gridColor
The color of the grid. |
protected Dimension |
preferredViewportSize
Used by the Scrollable interface to determine the initial visible area. |
protected int |
rowHeight
The height in pixels of each row in the table. |
protected int |
rowMargin
The height in pixels of the margin between the cells in each row. |
protected boolean |
rowSelectionAllowed
True if row selection is allowed in this table. |
protected Color |
selectionBackground
The background color of selected cells. |
protected Color |
selectionForeground
The foreground color of selected cells. |
protected ListSelectionModel |
selectionModel
The ListSelectionModel of the table, used to keep track of row selections. |
protected boolean |
showHorizontalLines
The table draws horizontal lines between cells if showHorizontalLines is true. |
protected boolean |
showVerticalLines
The table draws vertical lines between cells if showVerticalLines is true. |
protected JTableHeader |
tableHeader
The TableHeader working with the table. |
|
Constructor Summary |
JTable()
Constructs a default JTable that is initialized with a default
data model, a default column model, and a default selection
model. |
JTable(int numRows,
int numColumns)
Constructs a JTable with numRows
and numColumns of empty cells using
DefaultTableModel. |
JTable(Object[][] rowData,
Object[] columnNames)
Constructs a JTable to display the values in the two dimensional array,
rowData, with column names, columnNames. |
JTable(TableModel dm)
Constructs a JTable that is initialized with
dm as the data model, a default column model,
and a default selection model. |
JTable(TableModel dm,
TableColumnModel cm)
Constructs a JTable that is initialized with
dm as the data model, cm
as the column model, and a default selection model. |
JTable(TableModel dm,
TableColumnModel cm,
ListSelectionModel sm)
Constructs a JTable that is initialized with
dm as the data model, cm as the
column model, and sm as the selection model. |
JTable(Vector rowData,
Vector columnNames)
Constructs a JTable to display the values in the
Vector of Vectors, rowData,
with column names, columnNames. |
|
Method Summary |
void |
addColumn(TableColumn aColumn)
Appends aColumn to the end of the array of columns held by
this JTable's column model. |
void |
addColumnSelectionInterval(int index0,
int index1)
Adds the columns from index0 to index1,
inclusive, to the current selection. |
void |
addNotify()
Calls the configureEnclosingScrollPane method. |
void |
addRowSelectionInterval(int index0,
int index1)
Adds the rows from index0 to index1, inclusive, to
the current selection. |
void |
changeSelection(int rowIndex,
int columnIndex,
boolean toggle,
boolean extend)
Updates the selection models of the table, depending on the state of the
two flags: toggle and extend. |
void |
clearSelection()
Deselects all selected columns and rows. |
void |
columnAdded(TableColumnModelEvent e)
Invoked when a column is added to the table column model. |
int |
columnAtPoint(Point point)
Returns the index of the column that point lies in,
or -1 if the result is not in the range
[0, getColumnCount()-1]. |
void |
columnMarginChanged(ChangeEvent e)
Invoked when a column is moved due to a margin change. |
void |
columnMoved(TableColumnModelEvent e)
Invoked when a column is repositioned. |
void |
columnRemoved(TableColumnModelEvent e)
Invoked when a column is removed from the table column model. |
void |
columnSelectionChanged(ListSelectionEvent e)
Invoked when the selection model of the TableColumnModel
is changed. |
protected void |
configureEnclosingScrollPane()
If this JTable is the viewportView of an enclosing JScrollPane
(the usual situation), configure this ScrollPane by, amongst other things,
installing the table's tableHeader as the columnHeaderView of the scroll pane. |
int |
convertColumnIndexToModel(int viewColumnIndex)
Maps the index of the column in the view at
viewColumnIndex to the index of the column
in the table model. |
int |
convertColumnIndexToView(int modelColumnIndex)
Maps the index of the column in the table model at
modelColumnIndex to the index of the column
in the view. |
int |
convertRowIndexToModel(int viewRowIndex)
Maps the index of the row in terms of the view to the
underlying TableModel. |
int |
convertRowIndexToView(int modelRowIndex)
Maps the index of the row in terms of the
TableModel to the view. |
protected TableColumnModel |
createDefaultColumnModel()
Returns the default column model object, which is
a DefaultTableColumnModel. |
void |
createDefaultColumnsFromModel()
Creates default columns for the table from
the data model using the getColumnCount method
defined in the TableModel interface. |
protected TableModel |
createDefaultDataModel()
Returns the default table model object, which is
a DefaultTableModel. |
protected void |
createDefaultEditors()
Creates default cell editors for objects, numbers, and boolean values. |
protected void |
createDefaultRenderers()
Creates default cell renderers for objects, numbers, doubles, dates,
booleans, and icons. |
protected ListSelectionModel |
createDefaultSelectionModel()
Returns the default selection model object, which is
a DefaultListSelectionModel. |
protected JTableHeader |
createDefaultTableHeader()
Returns the default table header object, which is
a JTableHeader. |
static JScrollPane |
createScrollPaneForTable(JTable aTable)
Deprecated. As of Swing version 1.0.2,
replaced by new JScrollPane(aTable). |
void |
doLayout()
Causes this table to lay out its rows and columns. |
boolean |
editCellAt(int row,
int column)
Programmatically starts editing the cell at row and
column, if those indices are in the valid range, and
the cell at those indices is editable. |
boolean |
editCellAt(int row,
int column,
EventObject e)
Programmatically starts editing the cell at row and
column, if those indices are in the valid range, and
the cell at those indices is editable. |
void |
editingCanceled(ChangeEvent e)
Invoked when editing is canceled. |
void |
editingStopped(ChangeEvent e)
Invoked when editing is finished. |
AccessibleContext |
getAccessibleContext()
Gets the AccessibleContext associated with this JTable. |
boolean |
getAutoCreateColumnsFromModel()
Determines whether the table will create default columns from the model. |
boolean |
getAutoCreateRowSorter()
Returns true if whenever the model changes, a new
RowSorter should be created and installed
as the table's sorter; otherwise, returns false. |
int |
getAutoResizeMode()
Returns the auto resize mode of the table. |
TableCellEditor |
getCellEditor()
Returns the active cell editor, which is null if the table
is not currently editing. |
TableCellEditor |
getCellEditor(int row,
int column)
Returns an appropriate editor for the cell specified by
row and column. |
Rectangle |
getCellRect(int row,
int column,
boolean includeSpacing)
Returns a rectangle for the cell that lies at the intersection of
row and column. |
TableCellRenderer |
getCellRenderer(int row,
int column)
Returns an appropriate renderer for the cell specified by this row and
column. |
boolean |
getCellSelectionEnabled()
Returns true if both row and column selection models are enabled. |
TableColumn |
getColumn(Object identifier)
Returns the TableColumn object for the column in the table
whose identifier is equal to identifier, when compared using
equals. |
Class<?> |
getColumnClass(int column)
Returns the type of the column appearing in the view at
column position column. |
int |
getColumnCount()
Returns the number of columns in the column model. |
TableColumnModel |
getColumnModel()
Returns the TableColumnModel that contains all column information
of this table. |
String |
getColumnName(int column)
Returns the name of the column appearing in the view at
column position column. |
boolean |
getColumnSelectionAllowed()
Returns true if columns can be selected. |
TableCellEditor |
getDefaultEditor(Class<?> columnClass)
Returns the editor to be used when no editor has been set in
a TableColumn. |
TableCellRenderer |
getDefaultRenderer(Class<?> columnClass)
Returns the cell renderer to be used when no renderer has been set in
a TableColumn. |
boolean |
getDragEnabled()
Returns whether or not automatic drag handling is enabled. |
JTable.DropLocation |
getDropLocation()
Returns the location that this component should visually indicate
as the drop location during a DnD operation over the component,
or null if no location is to currently be shown. |
DropMode |
getDropMode()
Returns the drop mode for this component. |
int |
getEditingColumn()
Returns the index of the column that contains the cell currently
being edited. |
int |
getEditingRow()
Returns the index of the row that contains the cell currently
being edited. |
Component |
getEditorComponent()
Returns the component that is handling the editing session. |
boolean |
getFillsViewportHeight()
Returns whether or not this table is always made large enough
to fill the height of an enclosing viewport. |
Color |
getGridColor()
Returns the color used to draw grid lines. |
Dimension |
getIntercellSpacing()
Returns the horizontal and vertical space between cells. |
TableModel |
getModel()
Returns the TableModel that provides the data displayed by this
JTable. |
Dimension |
getPreferredScrollableViewportSize()
Returns the preferred size of the viewport for this table. |
Printable |
getPrintable(JTable.PrintMode printMode,
MessageFormat headerFormat,
MessageFormat footerFormat)
Return a Printable for use in printing this JTable. |
int |
getRowCount()
Returns the number of rows that can be shown in the
JTable, given unlimited space. |
int |
getRowHeight()
Returns the height of a table row, in pixels. |
int |
getRowHeight(int row)
Returns the height, in pixels, of the cells in row. |
int |
getRowMargin()
Gets the amount of empty space, in pixels, between cells. |
boolean |
getRowSelectionAllowed()
Returns true if rows can be selected. |
RowSorter<? extends TableModel> |
getRowSorter()
Returns the object responsible for sorting. |
int |
getScrollableBlockIncrement(Rectangle visibleRect,
int orientation,
int direction)
Returns visibleRect.height or
visibleRect.width,
depending on this table's orientation. |
boolean |
getScrollableTracksViewportHeight()
Returns false to indicate that the height of the viewport does
not determine the height of the table, unless
getFillsViewportHeight is true and the preferred height
of the table is smaller than the viewport's height. |
boolean |
getScrollableTracksViewportWidth()
Returns false if autoResizeMode is set to
AUTO_RESIZE_OFF, which indicates that the
width of the viewport does not determine the width
of the table. |
int |
getScrollableUnitIncrement(Rectangle visibleRect,
int orientation,
int direction)
Returns the scroll increment (in pixels) that completely exposes one new
row or column (depending on the orientation). |
int |
getSelectedColumn()
Returns the index of the first selected column,
-1 if no column is selected. |
int |
getSelectedColumnCount()
Returns the number of selected columns. |
int[] |
getSelectedColumns()
Returns the indices of all selected columns. |
int |
getSelectedRow()
Returns the index of the first selected row, -1 if no row is selected. |
int |
getSelectedRowCount()
Returns the number of selected rows. |
int[] |
getSelectedRows()
Returns the indices of all selected rows. |
Color |
getSelectionBackground()
Returns the background color for selected cells. |
Color |
getSelectionForeground()
Returns the foreground color for selected cells. |
ListSelectionModel |
getSelectionModel()
Returns the ListSelectionModel that is used to maintain row
selection state. |
boolean |
getShowHorizontalLines()
Returns true if the table draws horizontal lines between cells, false if it
doesn't. |
boolean |
getShowVerticalLines()
Returns true if the table draws vertical lines between cells, false if it
doesn't. |
boolean |
getSurrendersFocusOnKeystroke()
Returns true if the editor should get the focus
when keystrokes cause the editor to be activated |
JTableHeader |
getTableHeader()
Returns the tableHeader used by this JTable. |
String |
getToolTipText(MouseEvent event)
Overrides JComponent's getToolTipText
method in order to allow the renderer's tips to be used
if it has text set. |
TableUI |
getUI()
Returns the L&F object that renders this component. |
String |
getUIClassID()
Returns the suffix used to construct the name of the L&F class used to
render this component. |
boolean |
getUpdateSelectionOnSort()
Returns true if the selection should be updated after sorting. |
Object |
getValueAt(int row,
int column)
Returns the cell value at row and column. |
protected void |
initializeLocalVars()
Initializes table properties to their default values. |
boolean |
isCellEditable(int row,
int column)
Returns true if the cell at row and column
is editable. |
boolean |
isCellSelected(int row,
int column)
Returns true if the specified indices are in the valid range of rows
and columns and the cell at the specified position is selected. |
boolean |
isColumnSelected(int column)
Returns true if the specified index is in the valid range of columns,
and the column at that index is selected. |
boolean |
isEditing()
Returns true if a cell is being edited. |
boolean |
isRowSelected(int row)
Returns true if the specified index is in the valid range of rows,
and the row at that index is selected. |
void |
moveColumn(int column,
int targetColumn)
Moves the column column to the position currently
occupied by the column targetColumn in the view. |
protected String |
paramString()
Returns a string representation of this table. |
Component |
prepareEditor(TableCellEditor editor,
int row,
int column)
Prepares the editor by querying the data model for the value and
selection state of the cell at row, column. |
Component |
prepareRenderer(TableCellRenderer renderer,
int row,
int column)
Prepares the renderer by querying the data model for the
value and selection state
of the cell at row, column. |
boolean |
print()
A convenience method that displays a printing dialog, and then prints
this JTable in mode PrintMode.FIT_WIDTH,
with no header or footer text. |
boolean |
print(JTable.PrintMode printMode)
A convenience method that displays a printing dialog, and then prints
this JTable in the given printing mode,
with no header or footer text. |
boolean |
print(JTable.PrintMode printMode,
MessageFormat headerFormat,
MessageFormat footerFormat)
A convenience method that displays a printing dialog, and then prints
this JTable in the given printing mode,
with the specified header and footer text. |
boolean |
print(JTable.PrintMode printMode,
MessageFormat headerFormat,
MessageFormat footerFormat,
boolean showPrintDialog,
PrintRequestAttributeSet attr,
boolean interactive)
Prints this table, as specified by the fully featured
print
method, with the default printer specified as the print service. |
boolean |
print(JTable.PrintMode printMode,
MessageFormat headerFormat,
MessageFormat footerFormat,
boolean showPrintDialog,
PrintRequestAttributeSet attr,
boolean interactive,
PrintService service)
Prints this JTable. |
protected boolean |
processKeyBinding(KeyStroke ks,
KeyEvent e,
int condition,
boolean pressed)
Invoked to process the key bindings for ks as the result
of the KeyEvent e. |
void |
removeColumn(TableColumn aColumn)
Removes aColumn from this JTable's
array of columns. |
void |
removeColumnSelectionInterval(int index0,
int index1)
Deselects the columns from index0 to index1, inclusive. |
void |
removeEditor()
Discards the editor object and frees the real estate it used for
cell rendering. |
void |
removeNotify()
Calls the unconfigureEnclosingScrollPane method. |
void |
removeRowSelectionInterval(int index0,
int index1)
Deselects the rows from index0 to index1, inclusive. |
protected void |
resizeAndRepaint()
Equivalent to revalidate followed by repaint. |
int |
rowAtPoint(Point point)
Returns the index of the row that point lies in,
or -1 if the result is not in the range
[0, getRowCount()-1]. |
void |
selectAll()
Selects all rows, columns, and cells in the table. |
void |
setAutoCreateColumnsFromModel(boolean autoCreateColumnsFromModel)
Sets this table's autoCreateColumnsFromModel flag. |
void |
setAutoCreateRowSorter(boolean autoCreateRowSorter)
Specifies whether a RowSorter should be created for the
table whenever its model changes. |
void |
setAutoResizeMode(int mode)
Sets the table's auto resize mode when the table is resized. |
void |
setCellEditor(TableCellEditor anEditor)
Sets the active cell editor. |
void |
setCellSelectionEnabled(boolean cellSelectionEnabled)
Sets whether this table allows both a column selection and a
row selection to exist simultaneously. |
void |
setColumnModel(TableColumnModel columnModel)
Sets the column model for this table to newModel and registers
for listener notifications from the new column model. |
void |
setColumnSelectionAllowed(boolean columnSelectionAllowed)
Sets whether the columns in this model can be selected. |
void |
setColumnSelectionInterval(int index0,
int index1)
Selects the columns from index0 to index1,
inclusive. |
void |
setDefaultEditor(Class<?> columnClass,
TableCellEditor editor)
Sets a default cell editor to be used if no editor has been set in
a TableColumn. |
void |
setDefaultRenderer(Class<?> columnClass,
TableCellRenderer renderer)
Sets a default cell renderer to be used if no renderer has been set in
a TableColumn. |
void |
setDragEnabled(boolean b)
Turns on or off automatic drag handling. |
void |
setDropMode(DropMode dropMode)
Sets the drop mode for this component. |
void |
setEditingColumn(int aColumn)
Sets the editingColumn variable. |
void |
setEditingRow(int aRow)
Sets the editingRow variable. |
void |
setFillsViewportHeight(boolean fillsViewportHeight)
Sets whether or not this table is always made large enough
to fill the height of an enclosing viewport. |
void |
| |