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.
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 Vector
s of Object
s 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.
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.
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.
For the keyboard keys used by this component in the standard Look and Feel (L&F) renditions, see the JTable
key assignments.
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 java.beans.XMLEncoder.
Field Detail |
private static final String uiClassID
public static final int AUTO_RESIZE_OFF
public static final int AUTO_RESIZE_NEXT_COLUMN
public static final int AUTO_RESIZE_SUBSEQUENT_COLUMNS
public static final int AUTO_RESIZE_LAST_COLUMN
public static final int AUTO_RESIZE_ALL_COLUMNS
protected TableModel dataModel
TableModel
of the table.protected TableColumnModel columnModel
TableColumnModel
of the table.protected ListSelectionModel selectionModel
ListSelectionModel
of the table, used to keep track of row selections.protected JTableHeader tableHeader
TableHeader
working with the table.protected int rowHeight
protected int rowMargin
protected Color gridColor
protected boolean showHorizontalLines
showHorizontalLines
is true.protected boolean showVerticalLines
showVerticalLines
is true.protected int autoResizeMode
protected boolean autoCreateColumnsFromModel
TableModel
to build the default set of columns if this is true.protected Dimension preferredViewportSize
Scrollable
interface to determine the initial visible area.protected boolean rowSelectionAllowed
protected boolean cellSelectionEnabled
rowSelectionAllowed
property and the columnSelectionAllowed
property of the columnModel
instead. Or use the method getCellSelectionEnabled
.protected transient Component editorComp
Component
that is handling the editing.protected transient TableCellEditor cellEditor
protected transient int editingColumn
protected transient int editingRow
protected transient Hashtable defaultRenderersByColumnClass
getColumnClass
in the TableModel
interface.protected transient Hashtable defaultEditorsByColumnClass
getColumnClass
in the TableModel
interface.protected Color selectionForeground
protected Color selectionBackground
private boolean columnSelectionAdjusting
private boolean rowSelectionAdjusting
Constructor Detail |
public JTable()
JTable
that is initialized with a default data model, a default column model, and a default selection model.public JTable(TableModel dm)
JTable
that is initialized with dm
as the data model, a default column model, and a default selection model.dm
- the data model for the tablepublic JTable(TableModel dm, TableColumnModel cm)
JTable
that is initialized with dm
as the data model, cm
as the column model, and a default selection model.dm
- the data model for the tablecm
- the column model for the tablepublic JTable(TableModel dm, TableColumnModel cm, ListSelectionModel sm)
JTable
that is initialized with dm
as the data model, cm
as the column model, and sm
as the selection model. If any of the parameters are null
this method will initialize the table with the corresponding default model. The autoCreateColumnsFromModel
flag is set to false if cm
is non-null, otherwise it is set to true and the column model is populated with suitable TableColumns
for the columns in dm
.dm
- the data model for the tablecm
- the column model for the tablesm
- the row selection model for the tablepublic JTable(int numRows, int numColumns)
JTable
with numRows
and numColumns
of empty cells using DefaultTableModel
. The columns will have names of the form "A", "B", "C", etc.numRows
- the number of rows the table holdsnumColumns
- the number of columns the table holdspublic JTable(Vector rowData, Vector columnNames)
JTable
to display the values in the Vector
of Vectors
, rowData
, with column names, columnNames
. The Vectors
contained in rowData
should contain the values for that row. In other words, the value of the cell at row 1, column 5 can be obtained with the following code:
((Vector)rowData.elementAt(1)).elementAt(5);
rowData
- the data for the new tablecolumnNames
- names of each columnpublic JTable(Object[][] rowData, Object[] columnNames)
JTable
to display the values in the two dimensional array, rowData
, with column names, columnNames
. rowData
is an array of rows, so the value of the cell at row 1, column 5 can be obtained with the following code:
rowData[1][5];
All rows must be of the same length as columnNames
.
rowData
- the data for the new tablecolumnNames
- names of each columnMethod Detail |
public void addNotify()
configureEnclosingScrollPane
method.protected void configureEnclosingScrollPane()
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. When a JTable
is added to a JScrollPane
in the usual way, using new JScrollPane(myTable)
, addNotify
is called in the JTable
(when the table is added to the viewport). JTable
's addNotify
method in turn calls this method, which is protected so that this default installation procedure can be overridden by a subclass.public void removeNotify()
unconfigureEnclosingScrollPane
method.protected void unconfigureEnclosingScrollPane()
configureEnclosingScrollPane
by replacing the columnHeaderView
of the enclosing scroll pane with null
. JTable
's removeNotify
method calls this method, which is protected so that this default uninstallation procedure can be overridden by a subclass.public static JScrollPane createScrollPaneForTable(JTable aTable)
new JScrollPane(aTable)
.new JScrollPane(aTable)
.public void setTableHeader(JTableHeader tableHeader)
tableHeader
working with this JTable
to newHeader
. It is legal to have a null
tableHeader
.tableHeader
- new tableHeaderpublic JTableHeader getTableHeader()
tableHeader
used by this JTable
.tableHeader
used by this tablepublic void setRowHeight(int rowHeight)
rowHeight
, revalidates, and repaints. The height of the cells will be equal to the row height minus the row margin.rowHeight
- new row heightIllegalArgumentException
- if rowHeight
is less than 1public int getRowHeight()
public void setRowHeight(int row, int rowHeight)
row
to rowHeight
, revalidates, and repaints. The height of the cells in this row will be equal to the row height minus the row margin.row
- the row whose height is being changedrowHeight
- new row height, in pixelsIllegalArgumentException
- if rowHeight
is less than 1public int getRowHeight(int row)
row
.row
- the row whose height is to be returnedpublic void setRowMargin(int rowMargin)
rowMargin
- the number of pixels between cells in a rowpublic int getRowMargin()
getIntercellSpacing().height
.public void setIntercellSpacing(Dimension intercellSpacing)
rowMargin
and the columnMargin
-- the height and width of the space between cells -- to intercellSpacing
.intercellSpacing
- a Dimension
specifying the new width and height between cellspublic Dimension getIntercellSpacing()
public void setGridColor(Color gridColor)
gridColor
and redisplays. The default color is look and feel dependent.gridColor
- the new color of the grid linesIllegalArgumentException
- if gridColor
is null
public Color getGridColor()
public void setShowGrid(boolean showGrid)
showGrid
is true it does; if it is false it doesn't. There is no getShowGrid
method as this state is held in two variables -- showHorizontalLines
and showVerticalLines
-- each of which can be queried independently.showGrid
- true if table view should draw grid linespublic void setShowHorizontalLines(boolean showHorizontalLines)
showHorizontalLines
is true it does; if it is false it doesn't.showHorizontalLines
- true if table view should draw horizontal linespublic void setShowVerticalLines(boolean showVerticalLines)
showVerticalLines
is true it does; if it is false it doesn't.showVerticalLines
- true if table view should draw vertical linespublic boolean getShowHorizontalLines()
public boolean getShowVerticalLines()
public void setAutoResizeMode(int mode)
mode
- One of 5 legal values: AUTO_RESIZE_OFF, AUTO_RESIZE_NEXT_COLUMN, AUTO_RESIZE_SUBSEQUENT_COLUMNS, AUTO_RESIZE_LAST_COLUMN, AUTO_RESIZE_ALL_COLUMNSpublic int getAutoResizeMode()
public void setAutoCreateColumnsFromModel(boolean autoCreateColumnsFromModel)
autoCreateColumnsFromModel
flag. This method calls createDefaultColumnsFromModel
if autoCreateColumnsFromModel
changes from false to true.autoCreateColumnsFromModel
- true if JTable
should automatically create columnspublic boolean getAutoCreateColumnsFromModel()
setModel
will clear any existing columns and create new columns from the new model. Also, if the event in the tableChanged
notification specifies that the entire table changed, then the columns will be rebuilt. The default is true.public void createDefaultColumnsFromModel()
getColumnCount
method defined in the TableModel
interface. Clears any existing columns before creating the new columns based on information from the model.
public void setDefaultRenderer(Class columnClass, TableCellRenderer renderer)
TableColumn
. If renderer is null
, removes the default renderer for this column class.columnClass
- set the default cell renderer for this columnClassrenderer
- default cell renderer to be used for this columnClasspublic TableCellRenderer getDefaultRenderer(Class columnClass)
TableColumn
. During the rendering of cells the renderer is fetched from a Hashtable
of entries according to the class of the cells in the column. If there is no entry for this columnClass
the method returns the entry for the most specific superclass. The JTable
installs entries for Object
, Number
, and Boolean
, all of which can be modified or replaced.columnClass
- return the default cell renderer for this columnClasspublic void setDefaultEditor(Class columnClass, TableCellEditor editor)
TableColumn
. If no editing is required in a table, or a particular column in a table, uses the isCellEditable
method in the TableModel
interface to ensure that this JTable
will not start an editor in these columns. If editor is null
, removes the default editor for this column class.columnClass
- set the default cell editor for this columnClasseditor
- default cell editor to be used for this columnClasspublic TableCellEditor getDefaultEditor(Class columnClass)
TableColumn
. During the editing of cells the editor is fetched from a Hashtable
of entries according to the class of the cells in the column. If there is no entry for this columnClass
the method returns the entry for the most specific superclass. The JTable
installs entries for Object
, Number
, and Boolean
, all of which can be modified or replaced.columnClass
- return the default cell editor for this columnClasspublic void setDragEnabled(boolean b)
dragEnabled
property, which must be true
to enable automatic drag handling (the first part of drag and drop) on this component. The transferHandler
property needs to be set to a non-null
value for the drag to do anything. The default value of the dragEnabled
false. When automatic drag handling is enabled, most look and feels begin a drag-and-drop operation whenever the user presses the mouse button over a selection and then moves the mouse a few pixels. Setting this property to true
can therefore have a subtle effect on how selections behave.
Some look and feels might not support automatic drag and drop; they will ignore this property. You can work around such look and feels by modifying the component to directly call the exportAsDrag
method of a TransferHandler
.
b
- the value to set the dragEnabled
property toHeadlessException
- if b
is true
and GraphicsEnvironment.isHeadless()
returns true
public boolean getDragEnabled()
dragEnabled
property.dragEnabled
propertypublic void setSelectionMode(int selectionMode)
JTable
provides all the methods for handling column and row selection. When setting states, such as setSelectionMode
, it not only updates the mode for the row selection model but also sets similar values in the selection model of the columnModel
. If you want to have the row and column selection models operating in different modes, set them both directly.
Both the row and column selection models for JTable
default to using a DefaultListSelectionModel
so that JTable
works the same way as the JList
. See the setSelectionMode
method in JList
for details about the modes.
public void setRowSelectionAllowed(boolean rowSelectionAllowed)
rowSelectionAllowed
- true if this model will allow row selectionpublic boolean getRowSelectionAllowed()
public void setColumnSelectionAllowed(boolean columnSelectionAllowed)
columnSelectionAllowed
- true if this model will allow column selectionpublic boolean getColumnSelectionAllowed()
public void setCellSelectionEnabled(boolean cellSelectionEnabled)
isCellSelected
to change this default behavior. This method is equivalent to setting both the rowSelectionAllowed
property and columnSelectionAllowed
property of the columnModel
to the supplied value.cellSelectionEnabled
- true if simultaneous row and column selection is allowedpublic boolean getCellSelectionEnabled()
getRowSelectionAllowed() && getColumnSelectionAllowed()
.public void selectAll()
public void clearSelection()
public void setRowSelectionInterval(int index0, int index1)
index0
to index1
, inclusive.index0
- one end of the intervalindex1
- the other end of the intervalIllegalArgumentException
- if index0
or index1
lie outside [0, getRowCount()
-1]public void setColumnSelectionInterval(int index0, int index1)
index0
to index1
, inclusive.index0
- one end of the intervalindex1
- the other end of the intervalIllegalArgumentException
- if index0
or index1
lie outside [0, getColumnCount()
-1]public void addRowSelectionInterval(int index0, int index1)
index0
to index1
, inclusive, to the current selection.index0
- one end of the intervalindex1
- the other end of the intervalIllegalArgumentException
- if index0
or index1
lie outside [0, getRowCount()
-1]public void addColumnSelectionInterval(int index0, int index1)
index0
to index1
, inclusive, to the current selection.index0
- one end of the intervalindex1
- the other end of the intervalIllegalArgumentException
- if index0
or index1
lie outside [0, getColumnCount()
-1]public void removeRowSelectionInterval(int index0, int index1)
index0
to index1
, inclusive.index0
- one end of the intervalindex1
- the other end of the intervalIllegalArgumentException
- if index0
or index1
lie outside [0, getRowCount()
-1]public void removeColumnSelectionInterval(int index0, int index1)
index0
to index1
, inclusive.index0
- one end of the intervalindex1
- the other end of the intervalIllegalArgumentException
- if index0
or index1
lie outside [0, getColumnCount()
-1]public int getSelectedRow()
public int getSelectedColumn()
public int[] getSelectedRows()
public int[] getSelectedColumns()
public int getSelectedRowCount()
public int getSelectedColumnCount()
public boolean isRowSelected(int row)
row
is selected, where 0 is the first rowIllegalArgumentException
- if row
is not in the valid rangepublic boolean isColumnSelected(int column)
column
- the column in the column modelcolumn
is selected, where 0 is the first columnIllegalArgumentException
- if column
is not in the valid rangepublic boolean isCellSelected(int row, int column)
row
- the row being queriedcolumn
- the column being queried(row, column)
is selected, where the first row and first column are at index 0IllegalArgumentException
- if row
or column
are not in the valid rangepublic void changeSelection(int rowIndex, int columnIndex, boolean toggle, boolean extend)
toggle
and extend
. All changes to the selection that are the result of keyboard or mouse events received by the UI are channeled through this method so that the behavior may be overridden by a subclass. This implementation uses the following conventions:
toggle
: false, extend
: false. Clear the previous selection and ensure the new cell is selected. toggle
: false, extend
: true. Extend the previous selection to include the specified cell. toggle
: true, extend
: false. If the specified cell is selected, deselect it. If it is not selected, select it. toggle
: true, extend
: true. Leave the selection state as it is, but move the anchor index to the specified location. rowIndex
- affects the selection at row
columnIndex
- affects the selection at column
toggle
- see description aboveextend
- if true, extend the current selectionpublic Color getSelectionForeground()
Color
object for the foreground propertypublic void setSelectionForeground(Color selectionForeground)
The default value of this property is defined by the look and feel implementation.
This is a JavaBeans bound property.
selectionForeground
- the Color
to use in the foreground for selected list itemspublic Color getSelectionBackground()
Color
used for the background of selected list itemspublic void setSelectionBackground(Color selectionBackground)
The default value of this property is defined by the look and feel implementation.
This is a JavaBeans bound property.
selectionBackground
- the Color
to use for the background of selected cellspublic TableColumn getColumn(Object identifier)
TableColumn
object for the column in the table whose identifier is equal to identifier
, when compared using equals
.identifier
- the identifier objectTableColumn
object that matches the identifierIllegalArgumentException
- if identifier
is null
or no TableColumn
has this identifierpublic int convertColumnIndexToModel(int viewColumnIndex)
viewColumnIndex
to the index of the column in the table model. Returns the index of the corresponding column in the model. If viewColumnIndex
is less than zero, returns viewColumnIndex
.viewColumnIndex
- the index of the column in the viewpublic int convertColumnIndexToView(int modelColumnIndex)
modelColumnIndex
to the index of the column in the view. Returns the index of the corresponding column in the view; returns -1 if this column is not being displayed. If modelColumnIndex
is less than zero, returns modelColumnIndex
.modelColumnIndex
- the index of the column in the modelpublic int getRowCount()
public int getColumnCount()
public String getColumnName(int column)
column
.column
- the column in the view being queriedcolumn
in the view where the first column is column 0public Class getColumnClass(int column)
column
.column
- the column in the view being queriedcolumn
in the view where the first column is column 0public Object getValueAt(int row, int column)
row
and column
. Note: The column is specified in the table view's display order, and not in the TableModel
's column order. This is an important distinction because as the user rearranges the columns in the table, the column at a given index in the view will change. Meanwhile the user's actions never affect the model's column ordering.
row
- the row whose value is to be queriedcolumn
- the column whose value is to be queriedpublic void setValueAt(Object aValue, int row, int column)
row
and column
. Note: The column is specified in the table view's display order, and not in the TableModel
's column order. This is an important distinction because as the user rearranges the columns in the table, the column at a given index in the view will change. Meanwhile the user's actions never affect the model's column ordering. aValue
is the new value.
aValue
- the new valuerow
- the row of the cell to be changedcolumn
- the column of the cell to be changedpublic boolean isCellEditable(int row, int column)
row
and column
is editable. Otherwise, invoking setValueAt
on the cell will have no effect. Note: The column is specified in the table view's display order, and not in the TableModel
's column order. This is an important distinction because as the user rearranges the columns in the table, the column at a given index in the view will change. Meanwhile the user's actions never affect the model's column ordering.
row
- the row whose value is to be queriedcolumn
- the column whose value is to be queriedpublic void addColumn(TableColumn aColumn)
aColumn
to the end of the array of columns held by this JTable
's column model. If the column name of aColumn
is null
, sets the column name of aColumn
to the name returned by getModel().getColumnName()
. To add a column to this JTable
to display the modelColumn
'th column of data in the model with a given width
, cellRenderer
, and cellEditor
you can use:
addColumn(new TableColumn(modelColumn, width, cellRenderer, cellEditor));[Any of the
TableColumn
constructors can be used instead of this one.] The model column number is stored inside the TableColumn
and is used during rendering and editing to locate the appropriates data values in the model. The model column number does not change when columns are reordered in the view.aColumn
- the TableColumn
to be addedpublic void removeColumn(TableColumn aColumn)
aColumn
from this JTable
's array of columns. Note: this method does not remove the column of data from the model; it just removes the TableColumn
that was responsible for displaying it.aColumn
- the TableColumn
to be removedpublic void moveColumn(int column, int targetColumn)
column
to the position currently occupied by the column targetColumn
in the view. The old column at targetColumn
is shifted left or right to make room.column
- the index of column to be movedtargetColumn
- the new index of the columnpublic int columnAtPoint(Point point)
point
lies in, or -1 if the result is not in the range [0, getColumnCount()
-1].point
- the location of interestpoint
lies in, or -1 if the result is not in the range [0, getColumnCount()
-1]public int rowAtPoint(Point point)
point
lies in, or -1 if the result is not in the range [0, getRowCount()
-1].point
- the location of interestpoint
lies in, or -1 if the result is not in the range [0, getRowCount()
-1]public Rectangle getCellRect(int row, int column, boolean includeSpacing)
row
and column
. If includeSpacing
is true then the value returned has the full height and width of the row and column specified. If it is false, the returned rectangle is inset by the intercell spacing to return the true bounds of the rendering or editing component as it will be set during rendering. If the column index is valid but the row index is less than zero the method returns a rectangle with the y
and height
values set appropriately and the x
and width
values both set to zero. In general, when either the row or column indices indicate a cell outside the appropriate range, the method returns a rectangle depicting the closest edge of the closest cell that is within the table's range. When both row and column indices are out of range the returned rectangle covers the closest point of the closest cell.
In all cases, calculations that use this method to calculate results along one axis will not fail because of anomalies in calculations along the other axis. When the cell is not valid the includeSpacing
parameter is ignored.
row
- the row index where the desired cell is locatedcolumn
- the column index where the desired cell is located in the display; this is not necessarily the same as the column index in the data model for the table; the #convertColumnIndexToView(int) method may be used to convert a data model column index to a display column indexincludeSpacing
- if false, return the true cell bounds - computed by subtracting the intercell spacing from the height and widths of the column and row modelsrow
,column
public void doLayout()
JTable
's columns is equal to the width of the table. Before the layout begins the method gets the resizingColumn
of the tableHeader
. When the method is called as a result of the resizing of an enclosing window, the resizingColumn
is null
. This means that resizing has taken place "outside" the JTable
and the change - or "delta" - should be distributed to all of the columns regardless of this JTable
's automatic resize mode.
If the resizingColumn
is not null
, it is one of the columns in the table that has changed size rather than the table itself. In this case the auto-resize modes govern the way the extra (or deficit) space is distributed amongst the available columns.
The modes are:
Viewport
. If the JTable
is not enclosed in a JScrollPane
this may leave parts of the table invisible. JTable
, including the one that is being adjusted. JTable
makes adjustments to the widths of the columns it respects their minimum and maximum values absolutely. It is therefore possible that, even after this method is called, the total width of the columns is still not equal to the width of the table. When this happens the JTable
does not put itself in AUTO_RESIZE_OFF mode to bring up a scroll bar, or break other commitments of its current auto-resize mode -- instead it allows its bounds to be set larger (or smaller) than the total of the column minimum or maximum, meaning, either that there will not be enough room to display all of the columns, or that the columns will not fill the JTable
's bounds. These respectively, result in the clipping of some columns or an area being painted in the JTable
's background color during painting.
The mechanism for distributing the delta amongst the available columns is provided in a private method in the JTable
class:
adjustSizes(long targetSize, final Resizable3 r, boolean inverse)an explanation of which is provided in the following section.
Resizable3
is a private interface that allows any data structure containing a collection of elements with a size, preferred size, maximum size and minimum size to have its elements manipulated by the algorithm.
Call "DELTA" the difference between the target size and the sum of the preferred sizes of the elements in r. The individual sizes are calculated by taking the original preferred sizes and adding a share of the DELTA - that share being based on how far each preferred size is from its limiting bound (minimum or maximum).
Call the individual constraints min[i], max[i], and pref[i].
Call their respective sums: MIN, MAX, and PREF.
Each new size will be calculated using:
size[i] = pref[i] + delta[i]where each individual delta[i] is calculated according to:
If (DELTA < 0) we are in shrink mode where:
DELTA delta[i] = ------------ * (pref[i] - min[i]) (PREF - MIN)If (DELTA > 0) we are in expand mode where:
DELTA delta[i] = ------------ * (max[i] - pref[i]) (MAX - PREF)
The overall effect is that the total size moves that same percentage, k, towards the total minimum or maximum and that percentage guarantees accomodation of the required space, DELTA.
Naive evaluation of the formulae presented here would be subject to the aggregated rounding errors caused by doing this operation in finite precision (using ints). To deal with this, the multiplying factor above, is constantly recalculated and this takes account of the rounding errors in the previous iterations. The result is an algorithm that produces a set of integers whose values exactly sum to the supplied targetSize
, and does so by spreading the rounding errors evenly over the given elements.
When targetSize
is outside the [MIN, MAX] range, the algorithm sets all sizes to their appropriate limiting value (maximum or minimum).
public void sizeColumnsToFit(boolean lastColumnOnly)
doLayout()
.public void sizeColumnsToFit(int resizingColumn)
doLayout()
method instead.resizingColumn
- the column whose resizing made this adjustment necessary or -1 if there is no such columnpublic String getToolTipText(MouseEvent event)
JComponent
's getToolTipText
method in order to allow the renderer's tips to be used if it has text set. JTable
to properly display tooltips of its renderers JTable
must be a registered component with the ToolTipManager
. This is done automatically in initializeLocalVars
, but if at a later point JTable
is told setToolTipText(null)
it will unregister the table component, and no tips from renderers will display anymore.
public void setSurrendersFocusOnKeystroke(boolean surrendersFocusOnKeystroke)
surrendersFocusOnKeystroke
- true if the editor should get the focus when keystrokes cause the editor to be activatedpublic boolean getSurrendersFocusOnKeystroke()
public boolean editCellAt(int row, int column)
row
and column
, if the cell is editable. Note that this is a convenience method for editCellAt(int, int, null)
.row
- the row to be editedcolumn
- the column to be editedIllegalArgumentException
- if row
or column
is not in the valid rangepublic boolean editCellAt(int row, int column, EventObject e)
row
and column
, if the cell is editable. To prevent the JTable
from editing a particular table, column or cell value, return false from the isCellEditable
method in the TableModel
interface.row
- the row to be editedcolumn
- the column to be editede
- event to pass into shouldSelectCell
; note that as of Java 2 platform v1.2, the call to shouldSelectCell
is no longer madeIllegalArgumentException
- if row
or column
is not in the valid rangepublic boolean isEditing()
public Component getEditorComponent()
public int getEditingColumn()
public int getEditingRow()
public TableUI getUI()
TableUI
object that renders this componentpublic void setUI(TableUI ui)
ui
- the TableUI L&F objectpublic void updateUI()
UIManager
that the L&F has changed. Replaces the current UI object with the latest version from the UIManager
.public String getUIClassID()
public void setModel(TableModel dataModel)
newModel
and registers with it for listener notifications from the new data model.dataModel
- the new data source for this tableIllegalArgumentException
- if newModel
is null
public TableModel getModel()
TableModel
that provides the data displayed by this JTable
.TableModel
that provides the data displayed by this JTable
public void setColumnModel(TableColumnModel columnModel)
newModel
and registers for listener notifications from the new column model. Also sets the column model of the JTableHeader
to columnModel
.columnModel
- the new data source for this tableIllegalArgumentException
- if columnModel
is null
public TableColumnModel getColumnModel()
TableColumnModel
that contains all column information of this table.public void setSelectionModel(ListSelectionModel newModel)
newModel
and registers for listener notifications from the new selection model.newModel
- the new selection modelIllegalArgumentException
- if newModel
is null
public ListSelectionModel getSelectionModel()
ListSelectionModel
that is used to maintain row selection state.null
if row selection is not allowedpublic void tableChanged(TableModelEvent e)
TableModel
generates a TableModelEvent
. The TableModelEvent
should be constructed in the coordinate system of the model; the appropriate mapping to the view coordinate system is performed by this JTable
when it receives the event. Application code will not use these methods explicitly, they are used internally by JTable
.
Note that as of 1.3, this method clears the selection, if any.
public void columnAdded(TableColumnModelEvent e)
Application code will not use these methods explicitly, they are used internally by JTable.
public void columnRemoved(TableColumnModelEvent e)
Application code will not use these methods explicitly, they are used internally by JTable.
public void columnMoved(TableColumnModelEvent e)
Application code will not use these methods explicitly, they are used internally by JTable.
e
- the event receivedpublic void columnMarginChanged(ChangeEvent e)
Application code will not use these methods explicitly, they are used internally by JTable.
e
- the event receivedpublic void columnSelectionChanged(ListSelectionEvent e)
TableColumnModel
is changed. Application code will not use these methods explicitly, they are used internally by JTable.
e
- the event receivedpublic void valueChanged(ListSelectionEvent e)
Application code will not use these methods explicitly, they are used internally by JTable.
e
- the event receivedpublic void editingStopped(ChangeEvent e)
Application code will not use these methods explicitly, they are used internally by JTable.
e
- the event receivedpublic void editingCanceled(ChangeEvent e)
Application code will not use these methods explicitly, they are used internally by JTable.
e
- the event receivedpublic void setPreferredScrollableViewportSize(Dimension size)
size
- a Dimension
object specifying the preferredSize
of a JViewport
whose view is this tablepublic Dimension getPreferredScrollableViewportSize()
Dimension
object containing the preferredSize
of the JViewport
which displays this tablepublic int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction)
This method is called each time the user requests a unit scroll.
visibleRect
- the view area visible within the viewportorientation
- either SwingConstants.VERTICAL
or SwingConstants.HORIZONTAL
direction
- less than zero to scroll up/left, greater than zero for down/rightpublic int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction)
visibleRect.height
or visibleRect.width
, depending on this table's orientation. Note that as of Swing 1.1.1 (Java 2 v 1.2.2) the value returned will ensure that the viewport is cleanly aligned on a row boundary.visibleRect.height
or visibleRect.width
per the orientationpublic boolean getScrollableTracksViewportWidth()
autoResizeMode
is set to AUTO_RESIZE_OFF
, which indicates that the width of the viewport does not determine the width of the table. Otherwise returns true.autoResizeMode
is set to AUTO_RESIZE_OFF
, otherwise returns truepublic boolean getScrollableTracksViewportHeight()
protected void createDefaultRenderers()
protected void createDefaultEditors()
protected void initializeLocalVars()
protected TableModel createDefaultDataModel()
DefaultTableModel
. A subclass can override this method to return a different table model object.protected TableColumnModel createDefaultColumnModel()
DefaultTableColumnModel
. A subclass can override this method to return a different column model object.protected ListSelectionModel createDefaultSelectionModel()
DefaultListSelectionModel
. A subclass can override this method to return a different selection model object.protected JTableHeader createDefaultTableHeader()
JTableHeader
. A subclass can override this method to return a different table header object.protected void resizeAndRepaint()
revalidate
followed by repaint
.public TableCellEditor getCellEditor()
TableCellEditor
that does the editingpublic void setCellEditor(TableCellEditor anEditor)
cellEditor
variable.anEditor
- the TableCellEditor that does the editingpublic void setEditingColumn(int aColumn)
editingColumn
variable.aColumn
- the column of the cell to be editedpublic void setEditingRow(int aRow)
editingRow
variable.aRow
- the row of the cell to be editedpublic TableCellRenderer getCellRenderer(int row, int column)
TableColumn
for this column has a non-null renderer, returns that. If not, finds the class of the data in this column (using getColumnClass
) and returns the default renderer for this type of data. Note: Throughout the table package, the internal implementations always use this method to provide renderers so that this default behavior can be safely overridden by a subclass.
row
- the row of the cell to render, where 0 is the first rowcolumn
- the column of the cell to render, where 0 is the first columnnull
returns the default renderer for this type of objectpublic Component prepareRenderer(TableCellRenderer renderer, int row, int column)
row
, column
. Returns the component (may be a Component
or a JComponent
) under the event location. Note: Throughout the table package, the internal implementations always use this method to prepare renderers so that this default behavior can be safely overridden by a subclass.
renderer
- the TableCellRenderer
to preparerow
- the row of the cell to render, where 0 is the first rowcolumn
- the column of the cell to render, where 0 is the first columnComponent
under the event locationpublic TableCellEditor getCellEditor(int row, int column)
row
and column
. If the TableColumn
for this column has a non-null editor, returns that. If not, finds the class of the data in this column (using getColumnClass
) and returns the default editor for this type of data. Note: Throughout the table package, the internal implementations always use this method to provide editors so that this default behavior can be safely overridden by a subclass.
row
- the row of the cell to edit, where 0 is the first rowcolumn
- the column of the cell to edit, where 0 is the first columnnull
return the default editor for this type of cellpublic Component prepareEditor(TableCellEditor editor, int row, int column)
row
, column
. Note: Throughout the table package, the internal implementations always use this method to prepare editors so that this default behavior can be safely overridden by a subclass.
editor
- the TableCellEditor
to set uprow
- the row of the cell to edit, where 0 is the first rowcolumn
- the column of the cell to edit, where 0 is the first columnComponent
being editedpublic void removeEditor()
private void writeObject(ObjectOutputStream s)
protected String paramString()
null
.public AccessibleContext getAccessibleContext()