Class JTable
- All Implemented Interfaces:
ImageObserver, MenuContainer, Serializable, EventListener, Accessible, CellEditorListener, ListSelectionListener, RowSorterListener, TableColumnModelListener, TableModelListener, Scrollable
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 Integer.valueOf(row*col); }
};
JTable table = new JTable(dataModel);
JScrollPane scrollpane = new JScrollPane(table);
JTables are typically placed inside of a JScrollPane. By
default, a JTable will adjust its width such that
a horizontal scrollbar is unnecessary. To allow for a horizontal scrollbar,
invoke setAutoResizeMode(int) with AUTO_RESIZE_OFF.
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
autoCreateRowSorterproperty totrue, so that theJTablecreates aRowSorterfor 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(JTable.PrintMode, MessageFormat, 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 JavaBeans
has been added to the java.beans package.
Please see XMLEncoder.
- Since:
- 1.2
- See Also:
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionprotected classThis class implements accessibility support for theJTableclass.static final classA subclass ofTransferHandler.DropLocationrepresenting a drop location for aJTable.static enumPrinting modes, used in printingJTables.Nested classes/interfaces declared in class JComponent
JComponent.AccessibleJComponentModifier and TypeClassDescriptionclassInner class of JComponent used to provide default support for accessibility.Nested classes/interfaces declared in class Container
Container.AccessibleAWTContainerModifier and TypeClassDescriptionprotected classInner class of Container used to provide default support for accessibility.Nested classes/interfaces declared in class Component
Component.AccessibleAWTComponent, Component.BaselineResizeBehavior, Component.BltBufferStrategy, Component.FlipBufferStrategyModifier and TypeClassDescriptionprotected classInner class of Component used to provide default support for accessibility.static enumEnumeration of the common ways the baseline of a component can change as the size changes.protected classInner class for blitting offscreen surfaces to a component.protected classInner class for flipping buffers on a component. -
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final intDuring all resize operations, proportionately resize all columns.static final intDuring all resize operations, apply adjustments to the last column only.static final intWhen a column is adjusted in the UI, adjust the next column the opposite way.static final intDo not adjust column widths automatically; use a horizontal scrollbar instead.static final intDuring UI adjustment, change subsequent columns to preserve the total width; this is the default behavior.protected booleanThe table will query theTableModelto build the default set of columns if this is true.protected intDetermines 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 TableCellEditorThe active cell editor object, that overwrites the screen real estate occupied by the current cell and allows the user to change its contents.protected booleanObsolete as of Java 2 platform v1.3.protected TableColumnModelTheTableColumnModelof the table.protected TableModelTheTableModelof the table.A table of objects that display and edit the contents of a cell, indexed by class as declared ingetColumnClassin theTableModelinterface.A table of objects that display the contents of a cell, indexed by class as declared ingetColumnClassin theTableModelinterface.protected intIdentifies the column of the cell being edited.protected intIdentifies the row of the cell being edited.protected ComponentIf editing, theComponentthat is handling the editing.protected ColorThe color of the grid.protected DimensionUsed by theScrollableinterface to determine the initial visible area.protected intThe height in pixels of each row in the table.protected intThe height in pixels of the margin between the cells in each row.protected booleanTrue if row selection is allowed in this table.protected ColorThe background color of selected cells.protected ColorThe foreground color of selected cells.protected ListSelectionModelTheListSelectionModelof the table, used to keep track of row selections.protected booleanThe table draws horizontal lines between cells ifshowHorizontalLinesis true.protected booleanThe table draws vertical lines between cells ifshowVerticalLinesis true.protected JTableHeaderTheTableHeaderworking with the table.Fields declared in class JComponent
listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOWModifier and TypeFieldDescriptionprotected EventListenerListA list of event listeners for this component.static final StringThe comment to display when the cursor is over the component, also known as a "value tip", "flyover help", or "flyover label".protected ComponentUIThe look and feel delegate for this component.static final intConstant used by some of the APIs to mean that no condition is defined.static final intConstant used forregisterKeyboardActionthat means that the command should be invoked when the receiving component is an ancestor of the focused component or is itself the focused component.static final intConstant used forregisterKeyboardActionthat means that the command should be invoked when the component has the focus.static final intConstant used forregisterKeyboardActionthat means that the command should be invoked when the receiving component is in the window that has the focus or is itself the focused component.Fields declared in class Component
accessibleContext, BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENTModifier and TypeFieldDescriptionprotected AccessibleContextTheAccessibleContextassociated with thisComponent.static final floatEase-of-use constant forgetAlignmentY.static final floatEase-of-use constant forgetAlignmentYandgetAlignmentX.static final floatEase-of-use constant forgetAlignmentX.static final floatEase-of-use constant forgetAlignmentX.static final floatEase-of-use constant forgetAlignmentY().Fields declared in interface ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTHModifier and TypeFieldDescriptionstatic final intThis flag in the infoflags argument to imageUpdate indicates that an image which was being tracked asynchronously was aborted before production was complete.static final intThis flag in the infoflags argument to imageUpdate indicates that a static image which was previously drawn is now complete and can be drawn again in its final form.static final intThis flag in the infoflags argument to imageUpdate indicates that an image which was being tracked asynchronously has encountered an error.static final intThis flag in the infoflags argument to imageUpdate indicates that another complete frame of a multi-frame image which was previously drawn is now available to be drawn again.static final intThis flag in the infoflags argument to imageUpdate indicates that the height of the base image is now available and can be taken from the height argument to the imageUpdate callback method.static final intThis flag in the infoflags argument to imageUpdate indicates that the properties of the image are now available.static final intThis flag in the infoflags argument to imageUpdate indicates that more pixels needed for drawing a scaled variation of the image are available.static final intThis flag in the infoflags argument to imageUpdate indicates that the width of the base image is now available and can be taken from the width argument to the imageUpdate callback method. -
Constructor Summary
ConstructorsConstructorDescriptionJTable()Constructs a defaultJTablethat is initialized with a default data model, a default column model, and a default selection model.JTable(int numRows, int numColumns) Constructs aJTablewithnumRowsandnumColumnsof empty cells usingDefaultTableModel.Constructs aJTableto display the values in the two dimensional array,rowData, with column names,columnNames.Constructs aJTableto display the values in theVectorofVectors,rowData, with column names,columnNames.JTable(TableModel dm) Constructs aJTablethat is initialized withdmas the data model, a default column model, and a default selection model.JTable(TableModel dm, TableColumnModel cm) Constructs aJTablethat is initialized withdmas the data model,cmas the column model, and a default selection model.JTable(TableModel dm, TableColumnModel cm, ListSelectionModel sm) Constructs aJTablethat is initialized withdmas the data model,cmas the column model, andsmas the selection model. -
Method Summary
Modifier and TypeMethodDescriptionvoidaddColumn(TableColumn aColumn) AppendsaColumnto the end of the array of columns held by thisJTable's column model.voidaddColumnSelectionInterval(int index0, int index1) Adds the columns fromindex0toindex1, inclusive, to the current selection.voidCalls theconfigureEnclosingScrollPanemethod.voidaddRowSelectionInterval(int index0, int index1) Adds the rows fromindex0toindex1, inclusive, to the current selection.voidchangeSelection(int rowIndex, int columnIndex, boolean toggle, boolean extend) Updates the selection models of the table, depending on the state of the two flags:toggleandextend.voidDeselects all selected columns and rows.voidInvoked when a column is added to the table column model.intcolumnAtPoint(Point point) Returns the index of the column thatpointlies in, or -1 if the result is not in the range [0,getColumnCount()-1].voidInvoked when a column is moved due to a margin change.voidInvoked when a column is repositioned.voidInvoked when a column is removed from the table column model.voidInvoked when the selection model of theTableColumnModelis changed.protected voidIf thisJTableis theviewportViewof an enclosingJScrollPane(the usual situation), configure thisScrollPaneby, amongst other things, installing the table'stableHeaderas thecolumnHeaderViewof the scroll pane.intconvertColumnIndexToModel(int viewColumnIndex) Maps the index of the column in the view atviewColumnIndexto the index of the column in the table model.intconvertColumnIndexToView(int modelColumnIndex) Maps the index of the column in the table model atmodelColumnIndexto the index of the column in the view.intconvertRowIndexToModel(int viewRowIndex) Maps the index of the row in terms of the view to the underlyingTableModel.intconvertRowIndexToView(int modelRowIndex) Maps the index of the row in terms of theTableModelto the view.protected TableColumnModelReturns the default column model object, which is aDefaultTableColumnModel.voidCreates default columns for the table from the data model using thegetColumnCountmethod defined in theTableModelinterface.protected TableModelReturns the default table model object, which is aDefaultTableModel.protected voidCreates default cell editors for objects, numbers, and boolean values.protected voidCreates default cell renderers for objects, numbers, doubles, dates, booleans, and icons.protected ListSelectionModelReturns the default selection model object, which is aDefaultListSelectionModel.protected JTableHeaderReturns the default table header object, which is aJTableHeader.static JScrollPanecreateScrollPaneForTable(JTable aTable) Deprecated.voiddoLayout()Causes this table to lay out its rows and columns.booleaneditCellAt(int row, int column) Programmatically starts editing the cell atrowandcolumn, if those indices are in the valid range, and the cell at those indices is editable.booleaneditCellAt(int row, int column, EventObject e) Programmatically starts editing the cell atrowandcolumn, if those indices are in the valid range, and the cell at those indices is editable.voidInvoked when editing is canceled.voidInvoked when editing is finished.Gets the AccessibleContext associated with this JTable.booleanDetermines whether the table will create default columns from the model.booleanReturnstrueif whenever the model changes, a newRowSortershould be created and installed as the table's sorter; otherwise, returnsfalse.intReturns the auto resize mode of the table.Returns the active cell editor, which isnullif the table is not currently editing.getCellEditor(int row, int column) Returns an appropriate editor for the cell specified byrowandcolumn.getCellRect(int row, int column, boolean includeSpacing) Returns a rectangle for the cell that lies at the intersection ofrowandcolumn.getCellRenderer(int row, int column) Returns an appropriate renderer for the cell specified by this row and column.booleanReturns true if both row and column selection models are enabled.Returns theTableColumnobject for the column in the table whose identifier is equal toidentifier, when compared usingequals.Class<?> getColumnClass(int column) Returns the type of the column appearing in the view at column positioncolumn.intReturns the number of columns in the column model.Returns theTableColumnModelthat contains all column information of this table.getColumnName(int column) Returns the name of the column appearing in the view at column positioncolumn.booleanReturns true if columns can be selected.getDefaultEditor(Class<?> columnClass) Returns the editor to be used when no editor has been set in aTableColumn.getDefaultRenderer(Class<?> columnClass) Returns the cell renderer to be used when no renderer has been set in aTableColumn.booleanReturns whether or not automatic drag handling is enabled.final JTable.DropLocationReturns the location that this component should visually indicate as the drop location during a DnD operation over the component, ornullif no location is to currently be shown.final DropModeReturns the drop mode for this component.intReturns the index of the column that contains the cell currently being edited.intReturns the index of the row that contains the cell currently being edited.Returns the component that is handling the editing session.booleanReturns whether or not this table is always made large enough to fill the height of an enclosing viewport.Returns the color used to draw grid lines.Returns the horizontal and vertical space between cells.getModel()Returns theTableModelthat provides the data displayed by thisJTable.Returns the preferred size of the viewport for this table.getPrintable(JTable.PrintMode printMode, MessageFormat headerFormat, MessageFormat footerFormat) Return aPrintablefor use in printing this JTable.intReturns the number of rows that can be shown in theJTable, given unlimited space.intReturns the height of a table row, in pixels.intgetRowHeight(int row) Returns the height, in pixels, of the cells inrow.intGets the amount of empty space, in pixels, between cells.booleanReturns true if rows can be selected.RowSorter<? extends TableModel> Returns the object responsible for sorting.intgetScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) ReturnsvisibleRect.heightorvisibleRect.width, depending on this table's orientation.booleanReturnsfalseto indicate that the height of the viewport does not determine the height of the table, unlessgetFillsViewportHeightistrueand the preferred height of the table is smaller than the viewport's height.booleanReturns false ifautoResizeModeis set toAUTO_RESIZE_OFF, which indicates that the width of the viewport does not determine the width of the table.intgetScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) Returns the scroll increment (in pixels) that completely exposes one new row or column (depending on the orientation).intReturns the index of the first selected column, -1 if no column is selected.intReturns the number of selected columns.int[]Returns the indices of all selected columns.intReturns the index of the first selected row, -1 if no row is selected.intReturns the number of selected rows.int[]Returns the indices of all selected rows.Returns the background color for selected cells.Returns the foreground color for selected cells.Returns theListSelectionModelthat is used to maintain row selection state.booleanReturns true if the table draws horizontal lines between cells, false if it doesn't.booleanReturns true if the table draws vertical lines between cells, false if it doesn't.booleanReturns true if the editor should get the focus when keystrokes cause the editor to be activatedReturns thetableHeaderused by thisJTable.getToolTipText(MouseEvent event) OverridesJComponent'sgetToolTipTextmethod in order to allow the renderer's tips to be used if it has text set.getUI()Returns the L&F object that renders this component.Returns the suffix used to construct the name of the L&F class used to render this component.booleanReturns true if the selection should be updated after sorting.getValueAt(int row, int column) Returns the cell value atrowandcolumn.protected voidInitializes table properties to their default values.booleanisCellEditable(int row, int column) Returns true if the cell atrowandcolumnis editable.booleanisCellSelected(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.booleanisColumnSelected(int column) Returns true if the specified index is in the valid range of columns, and the column at that index is selected.booleanReturns true if a cell is being edited.booleanisRowSelected(int row) Returns true if the specified index is in the valid range of rows, and the row at that index is selected.voidmoveColumn(int column, int targetColumn) Moves the columncolumnto the position currently occupied by the columntargetColumnin the view.protected StringReturns a string representation of this table.prepareEditor(TableCellEditor editor, int row, int column) Prepares the editor by querying the data model for the value and selection state of the cell atrow,column.prepareRenderer(TableCellRenderer renderer, int row, int column) Prepares the renderer by querying the data model for the value and selection state of the cell atrow,column.booleanprint()A convenience method that displays a printing dialog, and then prints thisJTablein modePrintMode.FIT_WIDTH, with no header or footer text.booleanprint(JTable.PrintMode printMode) A convenience method that displays a printing dialog, and then prints thisJTablein the given printing mode, with no header or footer text.booleanprint(JTable.PrintMode printMode, MessageFormat headerFormat, MessageFormat footerFormat) A convenience method that displays a printing dialog, and then prints thisJTablein the given printing mode, with the specified header and footer text.booleanprint(JTable.PrintMode printMode, MessageFormat headerFormat, MessageFormat footerFormat, boolean showPrintDialog, PrintRequestAttributeSet attr, boolean interactive) Prints this table, as specified by the fully featuredprintmethod, with the default printer specified as the print service.booleanprint(JTable.PrintMode printMode, MessageFormat headerFormat, MessageFormat footerFormat, boolean showPrintDialog, PrintRequestAttributeSet attr, boolean interactive, PrintService service) Prints thisJTable.voidremoveColumn(TableColumn aColumn) RemovesaColumnfrom thisJTable's array of columns.voidremoveColumnSelectionInterval(int index0, int index1) Deselects the columns fromindex0toindex1, inclusive.voidDiscards the editor object and frees the real estate it used for cell rendering.voidCalls theunconfigureEnclosingScrollPanemethod.voidremoveRowSelectionInterval(int index0, int index1) Deselects the rows fromindex0toindex1, inclusive.protected voidEquivalent torevalidatefollowed byrepaint.introwAtPoint(Point point) Returns the index of the row thatpointlies in, or -1 if the result is not in the range [0,getRowCount()-1].voidSelects all rows, columns, and cells in the table.voidsetAutoCreateColumnsFromModel(boolean autoCreateColumnsFromModel) Sets this table'sautoCreateColumnsFromModelflag.voidsetAutoCreateRowSorter(boolean autoCreateRowSorter) Specifies whether aRowSortershould be created for the table whenever its model changes.voidsetAutoResizeMode(int mode) Sets the table's auto resize mode when the table is resized.voidsetCellEditor(TableCellEditor anEditor) Sets the active cell editor.voidsetCellSelectionEnabled(boolean cellSelectionEnabled) Sets whether this table allows both a column selection and a row selection to exist simultaneously.voidsetColumnModel(TableColumnModel columnModel) Sets the column model for this table tocolumnModeland registers for listener notifications from the new column model.voidsetColumnSelectionAllowed(boolean columnSelectionAllowed) Sets whether the columns in this model can be selected.voidsetColumnSelectionInterval(int index0, int index1) Selects the columns fromindex0toindex1, inclusive.voidsetDefaultEditor(Class<?> columnClass, TableCellEditor editor) Sets a default cell editor to be used if no editor has been set in aTableColumn.voidsetDefaultRenderer(Class<?> columnClass, TableCellRenderer renderer) Sets a default cell renderer to be used if no renderer has been set in aTableColumn.voidsetDragEnabled(boolean b) Turns on or off automatic drag handling.final voidsetDropMode(DropMode dropMode) Sets the drop mode for this component.voidsetEditingColumn(int aColumn) Sets theeditingColumnvariable.voidsetEditingRow(int aRow) Sets theeditingRowvariable.voidsetFillsViewportHeight(boolean fillsViewportHeight) Sets whether or not this table is always made large enough to fill the height of an enclosing viewport.voidsetGridColor(Color gridColor) Sets the color used to draw grid lines togridColorand redisplays.voidsetIntercellSpacing(Dimension intercellSpacing) Sets therowMarginand thecolumnMargin-- the height and width of the space between cells -- tointercellSpacing.voidsetModel(TableModel dataModel) Sets the data model for this table todataModeland registers with it for listener notifications from the new data model.voidSets the preferred size of the viewport for this table.voidsetRowHeight(int rowHeight) Sets the height, in pixels, of all cells torowHeight, revalidates, and repaints.voidsetRowHeight(int row, int rowHeight) Sets the height forrowtorowHeight, revalidates, and repaints.voidsetRowMargin(int rowMargin) Sets the amount of empty space between cells in adjacent rows.voidsetRowSelectionAllowed(boolean rowSelectionAllowed) Sets whether the rows in this model can be selected.voidsetRowSelectionInterval(int index0, int index1) Selects the rows fromindex0toindex1, inclusive.voidsetRowSorter(RowSorter<? extends TableModel> sorter) Sets theRowSorter.voidsetSelectionBackground(Color selectionBackground) Sets the background color for selected cells.voidsetSelectionForeground(Color selectionForeground) Sets the foreground color for selected cells.voidsetSelectionMode(int selectionMode) Sets the table's selection mode to allow only single selections, a single contiguous interval, or multiple intervals.voidsetSelectionModel(ListSelectionModel selectionModel) Sets the row selection model for this table toselectionModeland registers for listener notifications from the new selection model.voidsetShowGrid(boolean showGrid) Sets whether the table draws grid lines around cells.voidsetShowHorizontalLines(boolean showHorizontalLines) Sets whether the table draws horizontal lines between cells.voidsetShowVerticalLines(boolean showVerticalLines) Sets whether the table draws vertical lines between cells.voidsetSurrendersFocusOnKeystroke(boolean surrendersFocusOnKeystroke) Sets whether editors in this JTable get the keyboard focus when an editor is activated as a result of the JTable forwarding keyboard events for a cell.voidsetTableHeader(JTableHeader tableHeader) Sets thetableHeaderworking with thisJTabletonewHeader.voidSets the L&F object that renders this component and repaints.voidsetUpdateSelectionOnSort(boolean update) Specifies whether the selection should be updated after sorting.voidsetValueAt(Object aValue, int row, int column) Sets the value for the cell in the table model atrowandcolumn.voidsizeColumnsToFit(boolean lastColumnOnly) Deprecated.As of Swing version 1.0.3, replaced bydoLayout().voidsizeColumnsToFit(int resizingColumn) Obsolete as of Java 2 platform v1.4.voidRowSorterListenernotification that theRowSorterhas changed in some way.voidInvoked when this table'sTableModelgenerates aTableModelEvent.protected voidReverses the effect ofconfigureEnclosingScrollPaneby replacing thecolumnHeaderViewof the enclosing scroll pane withnull.voidupdateUI()Notification from theUIManagerthat the L&F has changed.voidInvoked when the row selection changes -- repaints to show the new selection.Methods declared in class JComponent
addAncestorListener, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBaseline, getBaselineResizeBehavior, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getPreferredSize, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, hide, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingOrigin, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, updateModifier and TypeMethodDescriptionvoidaddAncestorListener(AncestorListener listener) Registerslistenerso that it will receiveAncestorEventswhen it or any of its ancestors move or are made visible or invisible.voidAdds aVetoableChangeListenerto the listener list.voidcomputeVisibleRect(Rectangle visibleRect) Returns theComponent's "visible rect rectangle" - the intersection of the visible rectangles for this component and all of its ancestors.booleancontains(int x, int y) Gives the UI delegate an opportunity to define the precise shape of this component for the sake of mouse processing.Returns the instance ofJToolTipthat should be used to display the tooltip.voiddisable()Deprecated.As of JDK version 1.1, replaced byjava.awt.Component.setEnabled(boolean).voidenable()Deprecated.As of JDK version 1.1, replaced byjava.awt.Component.setEnabled(boolean).voidfirePropertyChange(String propertyName, boolean oldValue, boolean newValue) Support for reporting bound property changes for boolean properties.voidfirePropertyChange(String propertyName, int oldValue, int newValue) Support for reporting bound property changes for integer properties.protected voidfireVetoableChange(String propertyName, Object oldValue, Object newValue) Supports reporting constrained property changes.getActionForKeyStroke(KeyStroke aKeyStroke) Returns the object that will perform the action registered for a given keystroke.final ActionMapReturns theActionMapused to determine whatActionto fire for particularKeyStrokebinding.floatOverridesContainer.getAlignmentXto return the horizontal alignment.floatOverridesContainer.getAlignmentYto return the vertical alignment.Returns an array of all the ancestor listeners registered on this component.booleanGets theautoscrollsproperty.intgetBaseline(int width, int height) Returns the baseline.Returns an enum indicating how the baseline of the component changes as the size changes.Returns the border of this component ornullif no border is currently set.Stores the bounds of this component into "return value"rvand returnsrv.final ObjectgetClientProperty(Object key) Returns the value of the property with the specified key.protected GraphicsReturns the graphics object used to paint this component.ReturnsJPopupMenuthat assigned for this component.intgetConditionForKeyStroke(KeyStroke aKeyStroke) Returns the condition that determines whether a registered action occurs in response to the specified keystroke.intReturns the state of graphics debugging.static LocaleReturns the default locale used to initialize each JComponent's locale property upon creation.getFontMetrics(Font font) Gets theFontMetricsfor the specifiedFont.Returns this component's graphics context, which lets you draw on a component.intReturns the current height of this component.booleanReturns true if the JPopupMenu should be inherited from the parent.final InputMapReturns theInputMapthat is used when the component has focus.final InputMapgetInputMap(int condition) Returns theInputMapthat is used duringcondition.Returns the input verifier for this component.If a border has been set on this component, returns the border's insets; otherwise callssuper.getInsets.Returns anInsetsobject containing this component's inset values.<T extends EventListener>
T[]getListeners(Class<T> listenerType) Returns an array of all the objects currently registered asFooListeners upon thisJComponent.getLocation(Point rv) Stores the x,y origin of this component into "return value"rvand returnsrv.If the maximum size has been set to a non-nullvalue just returns it.If the minimum size has been set to a non-nullvalue just returns it.Deprecated.As of 1.4, replaced byFocusTraversalPolicy.getPopupLocation(MouseEvent event) Returns the preferred location to display the popup menu in this component's coordinate system.If thepreferredSizehas been set to a non-nullvalue just returns it.Returns theKeyStrokesthat will initiate registered actions.Returns theJRootPaneancestor for this component.Stores the width/height of this component into "return value"rvand returnsrv.getToolTipLocation(MouseEvent event) Returns the tooltip location in this component's coordinate system.Returns the tooltip string that has been set withsetToolTipText.Returns the top-level ancestor of this component (the containingWindow) ornullif this component has not been added to any container.Gets thetransferHandlerproperty.booleanReturns the value that indicates whether the input verifier for the current focus owner will be called before this component requests focus.Returns an array of all the vetoable change listeners registered on this component.Returns theComponent's "visible rectangle" - the intersection of this component's visible rectangle,new Rectangle(0, 0, getWidth(), getHeight()), and all of its ancestors' visible rectangles.intgetWidth()Returns the current width of this component.intgetX()Returns the current x coordinate of the component's origin.intgetY()Returns the current y coordinate of the component's origin.voidRequests that this Component get the input focus, and that this Component's top-level ancestor become the focused Window.voidhide()Deprecated.booleanReturns whether this component should use a buffer to paint.static booleanReturns true if this component is lightweight, that is, if it doesn't have a native window system peer.booleanDeprecated.As of 1.4, replaced byComponent.setFocusTraversalKeys(int, Set)andContainer.setFocusCycleRoot(boolean).booleanisOpaque()Returns true if this component is completely opaque.booleanReturns true if this component tiles its children -- that is, if it can guarantee that the children will not overlap.final booleanReturnstrueif the current painting operation on this component is part of aprintoperation.protected booleanReturnstrueif a paint triggered on a child component should cause painting to originate from this Component, or one of its ancestors.booleanReturns true if the component is currently painting a tile.booleanReturnstrueif thisJComponentshould get focus; otherwise returnsfalse.booleanIf this method returns true,revalidatecalls by descendants of this component will cause the entire tree beginning with this root to be validated.voidInvoked by Swing to draw components.protected voidPaints the component's border.protected voidPaints this component's children.protected voidCalls the UI delegate's paint method, if the UI delegate is non-null.voidpaintImmediately(int x, int y, int w, int h) Paints the specified region in this component and all of its descendants that overlap the region, immediately.voidPaints the specified region now.voidInvoke this method to print the component to the specifiedGraphics.voidInvoke this method to print the component.protected voidPrints the component's border.protected voidPrints this component's children.protected voidThis is invoked during a printing operation.protected voidProcesses any key events that the component itself recognizes.protected booleanprocessKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) Invoked to process the key bindings forksas the result of theKeyEvente.protected voidOverridesprocessKeyEventto process events.protected voidProcesses mouse events occurring on this component by dispatching them to any registeredMouseListenerobjects, refer toComponent.processMouseEvent(MouseEvent)for a complete description of this method.protected voidProcesses mouse motion events, such as MouseEvent.MOUSE_DRAGGED.final voidputClientProperty(Object key, Object value) Adds an arbitrary key/value "client property" to this component.voidregisterKeyboardAction(ActionListener anAction, String aCommand, KeyStroke aKeyStroke, int aCondition) This method is now obsolete, please use a combination ofgetActionMap()andgetInputMap()for similar behavior.voidregisterKeyboardAction(ActionListener anAction, KeyStroke aKeyStroke, int aCondition) This method is now obsolete, please use a combination ofgetActionMap()andgetInputMap()for similar behavior.voidremoveAncestorListener(AncestorListener listener) Unregisterslistenerso that it will no longer receiveAncestorEvents.voidRemoves aVetoableChangeListenerfrom the listener list.voidrepaint(long tm, int x, int y, int width, int height) Adds the specified region to the dirty region list if the component is showing.voidAdds the specified region to the dirty region list if the component is showing.booleanDeprecated.As of 1.4, replaced byFocusTraversalPolicy.getDefaultComponent(Container).requestFocus()voidRequests that thisComponentgets the input focus.booleanrequestFocus(boolean temporary) Requests that thisComponentgets the input focus.booleanRequests that thisComponentgets the input focus.protected booleanrequestFocusInWindow(boolean temporary) Requests that thisComponentgets the input focus.voidUnregisters all the bindings in the first tierInputMapsandActionMap.voidreshape(int x, int y, int w, int h) Deprecated.As of JDK 5, replaced byComponent.setBounds(int, int, int, int).voidSupports deferred automatic layout.voidscrollRectToVisible(Rectangle aRect) Forwards thescrollRectToVisible()message to theJComponent's parent.final voidSets theActionMaptoam.voidsetAlignmentX(float alignmentX) Sets the horizontal alignment.voidsetAlignmentY(float alignmentY) Sets the vertical alignment.voidsetAutoscrolls(boolean autoscrolls) Sets theautoscrollsproperty.voidsetBackground(Color bg) Sets the background color of this component.voidSets the border of this component.voidsetComponentPopupMenu(JPopupMenu popup) Sets theJPopupMenufor thisJComponent.voidsetDebugGraphicsOptions(int debugOptions) Enables or disables diagnostic information about every graphics operation performed within the component or one of its children.static voidSets the default locale used to initialize each JComponent's locale property upon creation.voidsetDoubleBuffered(boolean aFlag) Sets whether this component should use a buffer to paint.voidsetEnabled(boolean enabled) Sets whether or not this component is enabled.voidsetFocusTraversalKeys(int id, Set<? extends AWTKeyStroke> keystrokes) Sets the focus traversal keys for a given traversal operation for this Component.voidSets the font for this component.voidsetForeground(Color fg) Sets the foreground color of this component.voidsetInheritsPopupMenu(boolean value) Sets whether or notgetComponentPopupMenushould delegate to the parent if this component does not have aJPopupMenuassigned to it.final voidsetInputMap(int condition, InputMap map) Sets theInputMapto use under the conditionconditiontomap.voidsetInputVerifier(InputVerifier inputVerifier) Sets the input verifier for this component.voidsetMaximumSize(Dimension maximumSize) Sets the maximum size of this component to a constant value.voidsetMinimumSize(Dimension minimumSize) Sets the minimum size of this component to a constant value.voidsetNextFocusableComponent(Component aComponent) Deprecated.As of 1.4, replaced byFocusTraversalPolicyvoidsetOpaque(boolean isOpaque) If true the component paints every pixel within its bounds.voidsetPreferredSize(Dimension preferredSize) Sets the preferred size of this component.voidsetRequestFocusEnabled(boolean requestFocusEnabled) Provides a hint as to whether or not thisJComponentshould get focus.voidsetToolTipText(String text) Registers the text to display in a tool tip.voidsetTransferHandler(TransferHandler newHandler) Sets theTransferHandler, which provides support for transfer of data into and out of this component via cut/copy/paste and drag and drop.protected voidsetUI(ComponentUI newUI) Sets the look and feel delegate for this component.voidsetVerifyInputWhenFocusTarget(boolean verifyInputWhenFocusTarget) Sets the value to indicate whether input verifier for the current focus owner will be called before this component requests focus.voidsetVisible(boolean aFlag) Makes the component visible or invisible.voidunregisterKeyboardAction(KeyStroke aKeyStroke) This method is now obsolete.voidCallspaint.Methods declared in class Container
add, add, add, add, add, addContainerListener, addImpl, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setLayout, transferFocusDownCycle, validate, validateTreeModifier and TypeMethodDescriptionAppends the specified component to the end of this container.Adds the specified component to this container at the given position.voidAdds the specified component to the end of this container.voidAdds the specified component to this container with the specified constraints at the specified index.Adds the specified component to this container.voidAdds the specified container listener to receive container events from this container.protected voidAdds the specified component to this container at the specified index.voidAdds a PropertyChangeListener to the listener list.voidaddPropertyChangeListener(String propertyName, PropertyChangeListener listener) Adds a PropertyChangeListener to the listener list for a specific property.voidSets theComponentOrientationproperty of this container and all components contained within it.booleanareFocusTraversalKeysSet(int id) Returns whether the Set of focus traversal keys for the given focus traversal operation has been explicitly defined for this Container.intDeprecated.As of JDK version 1.1, replaced by getComponentCount().voidDeprecated.As of JDK version 1.1, replaced bydispatchEvent(AWTEvent e)findComponentAt(int x, int y) Locates the visible child component that contains the specified position.Locates the visible child component that contains the specified point.getComponent(int n) Gets the nth component in this container.getComponentAt(int x, int y) Locates the component that contains the x,y position.Gets the component that contains the specified point.intGets the number of components in this panel.Gets all the components in this container.intgetComponentZOrder(Component comp) Returns the z-order index of the component inside the container.Returns an array of all the container listeners registered on this container.getFocusTraversalKeys(int id) Returns the Set of focus traversal keys for a given traversal operation for this Container.Returns the focus traversal policy that will manage keyboard traversal of this Container's children, or null if this Container is not a focus cycle root.Gets the layout manager for this container.getMousePosition(boolean allowChildren) Returns the position of the mouse pointer in thisContainer's coordinate space if theContaineris under the mouse pointer, otherwise returnsnull.insets()Deprecated.As of JDK version 1.1, replaced bygetInsets().voidInvalidates the container.booleanChecks if the component is contained in the component hierarchy of this container.booleanReturns whether this Container is the root of a focus traversal cycle.booleanisFocusCycleRoot(Container container) Returns whether the specified Container is the focus cycle root of this Container's focus traversal cycle.final booleanReturns whether this container provides focus traversal policy.booleanReturns whether the focus traversal policy has been explicitly set for this Container.voidlayout()Deprecated.As of JDK version 1.1, replaced bydoLayout().voidlist(PrintStream out, int indent) Prints a listing of this container to the specified output stream.voidlist(PrintWriter out, int indent) Prints out a list, starting at the specified indentation, to the specified print writer.locate(int x, int y) Deprecated.As of JDK version 1.1, replaced bygetComponentAt(int, int).Deprecated.As of JDK version 1.1, replaced bygetMinimumSize().voidPaints each of the components in this container.Deprecated.As of JDK version 1.1, replaced bygetPreferredSize().voidPrints each of the components in this container.protected voidProcesses container events occurring on this container by dispatching them to any registered ContainerListener objects.protected voidProcesses events on this container.voidremove(int index) Removes the component, specified byindex, from this container.voidRemoves the specified component from this container.voidRemoves all the components from this container.voidRemoves the specified container listener so it no longer receives container events from this container.voidsetComponentZOrder(Component comp, int index) Moves the specified component to the specified z-order index in the container.voidsetFocusCycleRoot(boolean focusCycleRoot) Sets whether this Container is the root of a focus traversal cycle.voidSets the focus traversal policy that will manage keyboard traversal of this Container's children, if this Container is a focus cycle root.final voidsetFocusTraversalPolicyProvider(boolean provider) Sets whether this container will be used to provide focus traversal policy.voidsetLayout(LayoutManager mgr) Sets the layout manager for this container.voidTransfers the focus down one focus traversal cycle.voidvalidate()Validates this container and all of its subcomponents.protected voidRecursively descends the container tree and recomputes the layout for any subtrees marked as needing it (those marked as invalid).Methods declared in class Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, requestFocus, requestFocus, requestFocusInWindow, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setMixingCutoutShape, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusBackward, transferFocusUpCycleModifier and TypeMethodDescriptionbooleanDeprecated.As of JDK version 1.1, should register this component as ActionListener on component which fires action events.voidAdds the specified popup menu to the component.voidAdds the specified component listener to receive component events from this component.voidAdds the specified focus listener to receive focus events from this component when this component gains input focus.voidAdds the specified hierarchy bounds listener to receive hierarchy bounds events from this component when the hierarchy to which this container belongs changes.voidAdds the specified hierarchy listener to receive hierarchy changed events from this component when the hierarchy to which this container belongs changes.voidAdds the specified input method listener to receive input method events from this component.voidAdds the specified key listener to receive key events from this component.voidAdds the specified mouse listener to receive mouse events from this component.voidAdds the specified mouse motion listener to receive mouse motion events from this component.voidAdds the specified mouse wheel listener to receive mouse wheel events from this component.bounds()Deprecated.As of JDK version 1.1, replaced bygetBounds().intcheckImage(Image image, int width, int height, ImageObserver observer) Returns the status of the construction of a screen representation of the specified image.intcheckImage(Image image, ImageObserver observer) Returns the status of the construction of a screen representation of the specified image.protected AWTEventcoalesceEvents(AWTEvent existingEvent, AWTEvent newEvent) Potentially coalesce an event being posted with an existing event.booleanChecks whether this component "contains" the specified point, where the point's x and y coordinates are defined to be relative to the coordinate system of this component.createImage(int width, int height) Creates an off-screen drawable image to be used for double buffering.createImage(ImageProducer producer) Creates an image from the specified image producer.createVolatileImage(int width, int height) Creates a volatile off-screen drawable image to be used for double buffering.createVolatileImage(int width, int height, ImageCapabilities caps) Creates a volatile off-screen drawable image, with the given capabilities.protected final voiddisableEvents(long eventsToDisable) Disables the events defined by the specified event mask parameter from being delivered to this component.final voidDispatches an event to this component or one of its sub components.voidenable(boolean b) Deprecated.As of JDK version 1.1, replaced bysetEnabled(boolean).protected final voidenableEvents(long eventsToEnable) Enables the events defined by the specified event mask parameter to be delivered to this component.voidenableInputMethods(boolean enable) Enables or disables input method support for this component.voidfirePropertyChange(String propertyName, byte oldValue, byte newValue) Reports a bound property change.voidfirePropertyChange(String propertyName, char oldValue, char newValue) Reports a bound property change.voidfirePropertyChange(String propertyName, double oldValue, double newValue) Reports a bound property change.voidfirePropertyChange(String propertyName, float oldValue, float newValue) Reports a bound property change.voidfirePropertyChange(String propertyName, long oldValue, long newValue) Reports a bound property change.voidfirePropertyChange(String propertyName, short oldValue, short newValue) Reports a bound property change.protected voidfirePropertyChange(String propertyName, Object oldValue, Object newValue) Support for reporting bound property changes for Object properties.Gets the background color of this component.Gets the bounds of this component in the form of aRectangleobject.Gets the instance ofColorModelused to display the component on the output device.Returns an array of all the component listeners registered on this component.Retrieves the language-sensitive orientation that is to be used to order the elements or text within this component.Gets the cursor set in the component.Gets theDropTargetassociated with thisComponent.Returns the Container which is the focus cycle root of this Component's focus traversal cycle.Returns an array of all the focus listeners registered on this component.booleanReturns whether focus traversal keys are enabled for this Component.getFont()Gets the font of this component.Gets the foreground color of this component.Gets theGraphicsConfigurationassociated with thisComponent.Returns an array of all the hierarchy bounds listeners registered on this component.Returns an array of all the hierarchy listeners registered on this component.booleanReturns whether or not paint messages received from the operating system should be ignored.Gets the input context used by this component for handling the communication with input methods when text is entered in this component.Returns an array of all the input method listeners registered on this component.Gets the input method request handler which supports requests from input methods for this component.Returns an array of all the key listeners registered on this component.Gets the locale of this component.Gets the location of this component in the form of a point specifying the component's top-left corner.Gets the location of this component in the form of a point specifying the component's top-left corner in the screen's coordinate space.Returns an array of all the mouse listeners registered on this component.Returns an array of all the mouse motion listeners registered on this component.Returns the position of the mouse pointer in thisComponent's coordinate space if theComponentis directly under the mouse pointer, otherwise returnsnull.Returns an array of all the mouse wheel listeners registered on this component.getName()Gets the name of the component.Gets the parent of this component.Returns an array of all the property change listeners registered on this component.getPropertyChangeListeners(String propertyName) Returns an array of all the listeners which have been associated with the named property.getSize()Returns the size of this component in the form of aDimensionobject.Gets the toolkit of this component.final ObjectGets this component's locking object (the object that owns the thread synchronization monitor) for AWT component-tree and layout operations.booleanDeprecated.As of JDK version 1.1, replaced by processFocusEvent(FocusEvent).booleanhandleEvent(Event evt) Deprecated.As of JDK version 1.1 replaced by processEvent(AWTEvent).booleanhasFocus()Returnstrueif thisComponentis the focus owner.booleanimageUpdate(Image img, int infoflags, int x, int y, int w, int h) Repaints the component when the image has changed.booleaninside(int x, int y) Deprecated.As of JDK version 1.1, replaced by contains(int, int).booleanReturns whether the background color has been explicitly set for this Component.booleanReturns whether the cursor has been explicitly set for this Component.booleanDetermines whether this component is displayable.booleanDetermines whether this component is enabled.booleanReturns whether this Component can be focused.booleanReturnstrueif thisComponentis the focus owner.booleanDeprecated.As of 1.4, replaced byisFocusable().booleanReturns whether the font has been explicitly set for this Component.booleanReturns whether the foreground color has been explicitly set for this Component.booleanA lightweight component doesn't have a native toolkit peer.booleanReturns true if the maximum size has been set to a non-nullvalue otherwise returns false.booleanReturns whether or notsetMinimumSizehas been invoked with a non-null value.booleanReturns true if the preferred size has been set to a non-nullvalue otherwise returns false.booleanDetermines whether this component is showing on screen.booleanisValid()Determines whether this component is valid.booleanDetermines whether this component should be visible when its parent is visible.booleanDeprecated.As of JDK version 1.1, replaced by processKeyEvent(KeyEvent).booleanDeprecated.As of JDK version 1.1, replaced by processKeyEvent(KeyEvent).voidlist()Prints a listing of this component to the standard system output streamSystem.out.voidlist(PrintStream out) Prints a listing of this component to the specified output stream.voidlist(PrintWriter out) Prints a listing to the specified print writer.location()Deprecated.As of JDK version 1.1, replaced bygetLocation().booleanDeprecated.As of JDK version 1.1, replaced by processFocusEvent(FocusEvent).booleanDeprecated.As of JDK version 1.1, replaced by processMouseEvent(MouseEvent).booleanDeprecated.As of JDK version 1.1, replaced by processMouseMotionEvent(MouseEvent).booleanmouseEnter(Event evt, int x, int y) Deprecated.As of JDK version 1.1, replaced by processMouseEvent(MouseEvent).booleanDeprecated.As of JDK version 1.1, replaced by processMouseEvent(MouseEvent).booleanDeprecated.As of JDK version 1.1, replaced by processMouseMotionEvent(MouseEvent).booleanDeprecated.As of JDK version 1.1, replaced by processMouseEvent(MouseEvent).voidmove(int x, int y) Deprecated.As of JDK version 1.1, replaced bysetLocation(int, int).voidDeprecated.As of JDK version 1.1, replaced by transferFocus().voidPaints this component and all of its subcomponents.booleanDeprecated.As of JDK version 1.1, replaced by dispatchEvent(AWTEvent).booleanprepareImage(Image image, int width, int height, ImageObserver observer) Prepares an image for rendering on this component at the specified width and height.booleanprepareImage(Image image, ImageObserver observer) Prepares an image for rendering on this component.protected voidProcesses component events occurring on this component by dispatching them to any registeredComponentListenerobjects.protected voidProcesses focus events occurring on this component by dispatching them to any registeredFocusListenerobjects.protected voidProcesses hierarchy bounds events occurring on this component by dispatching them to any registeredHierarchyBoundsListenerobjects.protected voidProcesses hierarchy events occurring on this component by dispatching them to any registeredHierarchyListenerobjects.protected voidProcesses input method events occurring on this component by dispatching them to any registeredInputMethodListenerobjects.protected voidProcesses mouse wheel events occurring on this component by dispatching them to any registeredMouseWheelListenerobjects.voidremove(MenuComponent popup) Removes the specified popup menu from the component.voidRemoves the specified component listener so that it no longer receives component events from this component.voidRemoves the specified focus listener so that it no longer receives focus events from this component.voidRemoves the specified hierarchy bounds listener so that it no longer receives hierarchy bounds events from this component.voidRemoves the specified hierarchy listener so that it no longer receives hierarchy changed events from this component.voidRemoves the specified input method listener so that it no longer receives input method events from this component.voidRemoves the specified key listener so that it no longer receives key events from this component.voidRemoves the specified mouse listener so that it no longer receives mouse events from this component.voidRemoves the specified mouse motion listener so that it no longer receives mouse motion events from this component.voidRemoves the specified mouse wheel listener so that it no longer receives mouse wheel events from this component.voidRemoves a PropertyChangeListener from the listener list.voidremovePropertyChangeListener(String propertyName, PropertyChangeListener listener) Removes aPropertyChangeListenerfrom the listener list for a specific property.voidrepaint()Repaints this component.voidrepaint(int x, int y, int width, int height) Repaints the specified rectangle of this component.voidrepaint(long tm) Repaints the component.protected booleanrequestFocus(boolean temporary, FocusEvent.Cause cause) Requests by the reason ofcausethat thisComponentget the input focus, and that thisComponent's top-level ancestor become the focusedWindow.voidrequestFocus(FocusEvent.Cause cause) Requests by the reason ofcausethat this Component get the input focus, and that this Component's top-level ancestor become the focused Window.booleanRequests by the reason ofcausethat this Component get the input focus, if this Component's top-level ancestor is already the focused Window.voidresize(int width, int height) Deprecated.As of JDK version 1.1, replaced bysetSize(int, int).voidDeprecated.As of JDK version 1.1, replaced bysetSize(Dimension).voidsetBounds(int x, int y, int width, int height) Moves and resizes this component.voidMoves and resizes this component to conform to the new bounding rectangler.voidSets the language-sensitive orientation that is to be used to order the elements or text within this component.voidSets the cursor image to the specified cursor.voidAssociate aDropTargetwith this component.voidsetFocusable(boolean focusable) Sets the focusable state of this Component to the specified value.voidsetFocusTraversalKeysEnabled(boolean focusTraversalKeysEnabled) Sets whether focus traversal keys are enabled for this Component.voidsetIgnoreRepaint(boolean ignoreRepaint) Sets whether or not paint messages received from the operating system should be ignored.voidSets the locale of this component.voidsetLocation(int x, int y) Moves this component to a new location.voidsetLocation(Point p) Moves this component to a new location.voidsetMixingCutoutShape(Shape shape) Sets a 'mixing-cutout' shape for this lightweight component.voidSets the name of the component to the specified string.voidsetSize(int width, int height) Resizes this component so that it has widthwidthand heightheight.voidResizes this component so that it has widthd.widthand heightd.height.voidshow()Deprecated.As of JDK version 1.1, replaced bysetVisible(boolean).voidshow(boolean b) Deprecated.As of JDK version 1.1, replaced bysetVisible(boolean).size()Deprecated.As of JDK version 1.1, replaced bygetSize().toString()Returns a string representation of this component and its values.voidTransfers the focus to the next component, as though this Component were the focus owner.voidTransfers the focus to the previous component, as though this Component were the focus owner.voidTransfers the focus up one focus traversal cycle.Methods declared in class Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, waitModifier and TypeMethodDescriptionprotected Objectclone()Creates and returns a copy of this object.booleanIndicates whether some other object is "equal to" this one.protected voidfinalize()Deprecated, for removal: This API element is subject to removal in a future version.Finalization is deprecated and subject to removal in a future release.final Class<?> getClass()Returns the runtime class of thisObject.inthashCode()Returns a hash code value for this object.final voidnotify()Wakes up a single thread that is waiting on this object's monitor.final voidWakes up all threads that are waiting on this object's monitor.final voidwait()Causes the current thread to wait until it is awakened, typically by being notified or interrupted.final voidwait(long timeoutMillis) Causes the current thread to wait until it is awakened, typically by being notified or interrupted, or until a certain amount of real time has elapsed.final voidwait(long timeoutMillis, int nanos) Causes the current thread to wait until it is awakened, typically by being notified or interrupted, or until a certain amount of real time has elapsed.
-
Field Details
-
AUTO_RESIZE_OFF
public static final int AUTO_RESIZE_OFFDo not adjust column widths automatically; use a horizontal scrollbar instead.- See Also:
-
AUTO_RESIZE_NEXT_COLUMN
public static final int AUTO_RESIZE_NEXT_COLUMNWhen a column is adjusted in the UI, adjust the next column the opposite way.- See Also:
-
AUTO_RESIZE_SUBSEQUENT_COLUMNS
public static final int AUTO_RESIZE_SUBSEQUENT_COLUMNSDuring UI adjustment, change subsequent columns to preserve the total width; this is the default behavior.- See Also:
-
AUTO_RESIZE_LAST_COLUMN
public static final int AUTO_RESIZE_LAST_COLUMNDuring all resize operations, apply adjustments to the last column only.- See Also:
-
AUTO_RESIZE_ALL_COLUMNS
public static final int AUTO_RESIZE_ALL_COLUMNSDuring all resize operations, proportionately resize all columns.- See Also:
-
dataModel
TheTableModelof the table. -
columnModel
TheTableColumnModelof the table. -
selectionModel
TheListSelectionModelof the table, used to keep track of row selections. -
tableHeader
TheTableHeaderworking with the table. -
rowHeight
protected int rowHeightThe height in pixels of each row in the table. -
rowMargin
protected int rowMarginThe height in pixels of the margin between the cells in each row. -
gridColor
The color of the grid. -
showHorizontalLines
protected boolean showHorizontalLinesThe table draws horizontal lines between cells ifshowHorizontalLinesis true. -
showVerticalLines
protected boolean showVerticalLinesThe table draws vertical lines between cells ifshowVerticalLinesis true. -
autoResizeMode
protected int autoResizeModeDetermines 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. -
autoCreateColumnsFromModel
protected boolean autoCreateColumnsFromModelThe table will query theTableModelto build the default set of columns if this is true. -
preferredViewportSize
Used by theScrollableinterface to determine the initial visible area. -
rowSelectionAllowed
protected boolean rowSelectionAllowedTrue if row selection is allowed in this table. -
cellSelectionEnabled
protected boolean cellSelectionEnabledObsolete as of Java 2 platform v1.3. Please use therowSelectionAllowedproperty and thecolumnSelectionAllowedproperty of thecolumnModelinstead. Or use the methodgetCellSelectionEnabled. -
editorComp
If editing, theComponentthat is handling the editing. -
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.nullif the table isn't currently editing. -
editingColumn
protected transient int editingColumnIdentifies the column of the cell being edited. -
editingRow
protected transient int editingRowIdentifies the row of the cell being edited. -
defaultRenderersByColumnClass
-
defaultEditorsByColumnClass
-
selectionForeground
The foreground color of selected cells. -
selectionBackground
The background color of selected cells.
-
-
Constructor Details
-
JTable
public JTable()Constructs a defaultJTablethat is initialized with a default data model, a default column model, and a default selection model.- See Also:
-
JTable
Constructs aJTablethat is initialized withdmas the data model, a default column model, and a default selection model.- Parameters:
dm- the data model for the table- See Also:
-
JTable
Constructs aJTablethat is initialized withdmas the data model,cmas the column model, and a default selection model.- Parameters:
dm- the data model for the tablecm- the column model for the table- See Also:
-
JTable
Constructs aJTablethat is initialized withdmas the data model,cmas the column model, andsmas the selection model. If any of the parameters arenullthis method will initialize the table with the corresponding default model. TheautoCreateColumnsFromModelflag is set to false ifcmis non-null, otherwise it is set to true and the column model is populated with suitableTableColumnsfor the columns indm.- Parameters:
dm- the data model for the tablecm- the column model for the tablesm- the row selection model for the table- See Also:
-
JTable
public JTable(int numRows, int numColumns) Constructs aJTablewithnumRowsandnumColumnsof empty cells usingDefaultTableModel. The columns will have names of the form "A", "B", "C", etc.- Parameters:
numRows- the number of rows the table holdsnumColumns- the number of columns the table holds- See Also:
-
JTable
Constructs aJTableto display the values in theVectorofVectors,rowData, with column names,columnNames. TheVectorscontained inrowDatashould 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);
- Parameters:
rowData- the data for the new tablecolumnNames- names of each column
-
JTable
Constructs aJTableto display the values in the two dimensional array,rowData, with column names,columnNames.rowDatais 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.- Parameters:
rowData- the data for the new tablecolumnNames- names of each column
-
-
Method Details
-
addNotify
public void addNotify()Calls theconfigureEnclosingScrollPanemethod.- Overrides:
addNotifyin classJComponent- See Also:
-
configureEnclosingScrollPane
protected void configureEnclosingScrollPane()If thisJTableis theviewportViewof an enclosingJScrollPane(the usual situation), configure thisScrollPaneby, amongst other things, installing the table'stableHeaderas thecolumnHeaderViewof the scroll pane. When aJTableis added to aJScrollPanein the usual way, usingnew JScrollPane(myTable),addNotifyis called in theJTable(when the table is added to the viewport).JTable'saddNotifymethod in turn calls this method, which is protected so that this default installation procedure can be overridden by a subclass.- See Also:
-
removeNotify
public void removeNotify()Calls theunconfigureEnclosingScrollPanemethod.- Overrides:
removeNotifyin classJComponent- See Also:
-
unconfigureEnclosingScrollPane
protected void unconfigureEnclosingScrollPane()Reverses the effect ofconfigureEnclosingScrollPaneby replacing thecolumnHeaderViewof the enclosing scroll pane withnull.JTable'sremoveNotifymethod calls this method, which is protected so that this default uninstallation procedure can be overridden by a subclass.- Since:
- 1.3
- See Also:
-
createScrollPaneForTable
Deprecated.As of Swing version 1.0.2, replaced bynew JScrollPane(aTable).Equivalent tonew JScrollPane(aTable).- Parameters:
aTable- aJTableto be used for the scroll pane- Returns:
- a
JScrollPanecreated usingaTable
-
setTableHeader
@BeanProperty(description="The JTableHeader instance which renders the column headers.") public void setTableHeader(JTableHeader tableHeader) Sets thetableHeaderworking with thisJTabletonewHeader. It is legal to have anulltableHeader.- Parameters:
tableHeader- new tableHeader- See Also:
-
getTableHeader
Returns thetableHeaderused by thisJTable.- Returns:
- the
tableHeaderused by this table - See Also:
-
setRowHeight
@BeanProperty(description="The height of the specified row.") public void setRowHeight(int rowHeight) Sets the height, in pixels, of all cells torowHeight, revalidates, and repaints. The height of the cells will be equal to the row height minus the row margin.- Parameters:
rowHeight- new row height- Throws:
IllegalArgumentException- ifrowHeightis less than 1- See Also:
-
getRowHeight
public int getRowHeight()Returns the height of a table row, in pixels.- Returns:
- the height in pixels of a table row
- See Also:
-
setRowHeight
@BeanProperty(description="The height in pixels of the cells in <code>row</code>") public void setRowHeight(int row, int rowHeight) Sets the height forrowtorowHeight, revalidates, and repaints. The height of the cells in this row will be equal to the row height minus the row margin.- Parameters:
row- the row whose height is being changedrowHeight- new row height, in pixels- Throws:
IllegalArgumentException- ifrowHeightis less than 1- Since:
- 1.3
-
getRowHeight
public int getRowHeight(int row) Returns the height, in pixels, of the cells inrow.- Parameters:
row- the row whose height is to be returned- Returns:
- the height, in pixels, of the cells in the row
- Since:
- 1.3
-
setRowMargin
@BeanProperty(description="The amount of space between cells.") public void setRowMargin(int rowMargin) Sets the amount of empty space between cells in adjacent rows.- Parameters:
rowMargin- the number of pixels between cells in a row- See Also:
-
getRowMargin
public int getRowMargin()Gets the amount of empty space, in pixels, between cells. Equivalent to:getIntercellSpacing().height.- Returns:
- the number of pixels between cells in a row
- See Also:
-
setIntercellSpacing
@BeanProperty(bound=false, description="The spacing between the cells, drawn in the background color of the JTable.") public void setIntercellSpacing(Dimension intercellSpacing) Sets therowMarginand thecolumnMargin-- the height and width of the space between cells -- tointercellSpacing.- Parameters:
intercellSpacing- aDimensionspecifying the new width and height between cells- See Also:
-
getIntercellSpacing
Returns the horizontal and vertical space between cells. The default spacing is look and feel dependent.- Returns:
- the horizontal and vertical spacing between cells
- See Also:
-
setGridColor
Sets the color used to draw grid lines togridColorand redisplays. The default color is look and feel dependent.- Parameters:
gridColor- the new color of the grid lines- Throws:
IllegalArgumentException- ifgridColorisnull- See Also:
-
getGridColor
Returns the color used to draw grid lines. The default color is look and feel dependent.- Returns:
- the color used to draw grid lines
- See Also:
-
setShowGrid
@BeanProperty(description="Whether grid lines are drawn around the cells.") public void setShowGrid(boolean showGrid) Sets whether the table draws grid lines around cells. IfshowGridis true it does; if it is false it doesn't. There is nogetShowGridmethod as this state is held in two variables --showHorizontalLinesandshowVerticalLines-- each of which can be queried independently.- Parameters:
showGrid- true if table view should draw grid lines- See Also:
-
setShowHorizontalLines
@BeanProperty(description="Whether horizontal lines should be drawn in between the cells.") public void setShowHorizontalLines(boolean showHorizontalLines) Sets whether the table draws horizontal lines between cells. IfshowHorizontalLinesis true it does; if it is false it doesn't.- Parameters:
showHorizontalLines- true if table view should draw horizontal lines- See Also:
-
setShowVerticalLines
@BeanProperty(description="Whether vertical lines should be drawn in between the cells.") public void setShowVerticalLines(boolean showVerticalLines) Sets whether the table draws vertical lines between cells. IfshowVerticalLinesis true it does; if it is false it doesn't.- Parameters:
showVerticalLines- true if table view should draw vertical lines- See Also:
-
getShowHorizontalLines
public boolean getShowHorizontalLines()Returns true if the table draws horizontal lines between cells, false if it doesn't. The default value is look and feel dependent.- Returns:
- true if the table draws horizontal lines between cells, false if it doesn't
- See Also:
-
getShowVerticalLines
public boolean getShowVerticalLines()Returns true if the table draws vertical lines between cells, false if it doesn't. The default value is look and feel dependent.- Returns:
- true if the table draws vertical lines between cells, false if it doesn't
- See Also:
-
setAutoResizeMode
@BeanProperty(enumerationValues={"JTable.AUTO_RESIZE_OFF","JTable.AUTO_RESIZE_NEXT_COLUMN","JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS","JTable.AUTO_RESIZE_LAST_COLUMN","JTable.AUTO_RESIZE_ALL_COLUMNS"}, description="Whether the columns should adjust themselves automatically.") public void setAutoResizeMode(int mode) Sets the table's auto resize mode when the table is resized. For further information on how the different resize modes work, seedoLayout().- Parameters:
mode- One of 5 legal values: AUTO_RESIZE_OFF, AUTO_RESIZE_NEXT_COLUMN, AUTO_RESIZE_SUBSEQUENT_COLUMNS, AUTO_RESIZE_LAST_COLUMN, AUTO_RESIZE_ALL_COLUMNS- See Also:
-
getAutoResizeMode
public int getAutoResizeMode()Returns the auto resize mode of the table. The default mode is AUTO_RESIZE_SUBSEQUENT_COLUMNS.- Returns:
- the autoResizeMode of the table
- See Also:
-
setAutoCreateColumnsFromModel
@BeanProperty(description="Automatically populates the columnModel when a new TableModel is submitted.") public void setAutoCreateColumnsFromModel(boolean autoCreateColumnsFromModel) Sets this table'sautoCreateColumnsFromModelflag. This method callscreateDefaultColumnsFromModelifautoCreateColumnsFromModelchanges from false to true.- Parameters:
autoCreateColumnsFromModel- true ifJTableshould automatically create columns- See Also:
-
getAutoCreateColumnsFromModel
public boolean getAutoCreateColumnsFromModel()Determines whether the table will create default columns from the model. If true,setModelwill clear any existing columns and create new columns from the new model. Also, if the event in thetableChangednotification specifies that the entire table changed, then the columns will be rebuilt. The default is true.- Returns:
- the autoCreateColumnsFromModel of the table
- See Also:
-
createDefaultColumnsFromModel
public void createDefaultColumnsFromModel()Creates default columns for the table from the data model using thegetColumnCountmethod defined in theTableModelinterface.Clears any existing columns before creating the new columns based on information from the model.
- See Also:
-
setDefaultRenderer
Sets a default cell renderer to be used if no renderer has been set in aTableColumn. If renderer isnull, removes the default renderer for this column class.- Parameters:
columnClass- set the default cell renderer for this columnClassrenderer- default cell renderer to be used for this columnClass- See Also:
-
getDefaultRenderer
Returns the cell renderer to be used when no renderer has been set in aTableColumn. During the rendering of cells the renderer is fetched from aHashtableof entries according to the class of the cells in the column. If there is no entry for thiscolumnClassthe method returns the entry for the most specific superclass. TheJTableinstalls entries forObject,Number, andBoolean, all of which can be modified or replaced.- Parameters:
columnClass- return the default cell renderer for this columnClass- Returns:
- the renderer for this columnClass
- See Also:
-
setDefaultEditor
Sets a default cell editor to be used if no editor has been set in aTableColumn. If no editing is required in a table, or a particular column in a table, uses theisCellEditablemethod in theTableModelinterface to ensure that thisJTablewill not start an editor in these columns. If editor isnull, removes the default editor for this column class.- Parameters:
columnClass- set the default cell editor for this columnClasseditor- default cell editor to be used for this columnClass- See Also:
-
getDefaultEditor
Returns the editor to be used when no editor has been set in aTableColumn. During the editing of cells the editor is fetched from aHashtableof entries according to the class of the cells in the column. If there is no entry for thiscolumnClassthe method returns the entry for the most specific superclass. TheJTableinstalls entries forObject,Number, andBoolean, all of which can be modified or replaced.- Parameters:
columnClass- return the default cell editor for this columnClass- Returns:
- the default cell editor to be used for this columnClass
- See Also:
-
setDragEnabled
@BeanProperty(bound=false, description="determines whether automatic drag handling is enabled") public void setDragEnabled(boolean b) Turns on or off automatic drag handling. In order to enable automatic drag handling, this property should be set totrue, and the table'sTransferHandlerneeds to benon-null. The default value of thedragEnabledproperty isfalse.The job of honoring this property, and recognizing a user drag gesture, lies with the look and feel implementation, and in particular, the table's
TableUI. When automatic drag handling is enabled, most look and feels (including those that subclassBasicLookAndFeel) begin a drag and drop operation whenever the user presses the mouse button over an item (in single selection mode) or a selection (in other selection modes) and then moves the mouse a few pixels. Setting this property totruecan therefore have a subtle effect on how selections behave.If a look and feel is used that ignores this property, you can still begin a drag and drop operation by calling
exportAsDragon the table'sTransferHandler.- Parameters:
b- whether or not to enable automatic drag handling- Throws:
HeadlessException- ifbistrueandGraphicsEnvironment.isHeadless()returnstrue- Since:
- 1.4
- See Also:
-
getDragEnabled
public boolean getDragEnabled()Returns whether or not automatic drag handling is enabled.- Returns:
- the value of the
dragEnabledproperty - Since:
- 1.4
- See Also:
-
setDropMode
Sets the drop mode for this component. For backward compatibility, the default for this property isDropMode.USE_SELECTION. Usage of one of the other modes is recommended, however, for an improved user experience.DropMode.ON, for instance, offers similar behavior of showing items as selected, but does so without affecting the actual selection in the table.JTablesupports the following drop modes:DropMode.USE_SELECTIONDropMode.ONDropMode.INSERTDropMode.INSERT_ROWSDropMode.INSERT_COLSDropMode.ON_OR_INSERTDropMode.ON_OR_INSERT_ROWSDropMode.ON_OR_INSERT_COLS
The drop mode is only meaningful if this component has a
TransferHandlerthat accepts drops.- Parameters:
dropMode- the drop mode to use- Throws:
IllegalArgumentException- if the drop mode is unsupported ornull- Since:
- 1.6
- See Also:
-
getDropMode
Returns the drop mode for this component.- Returns:
- the drop mode for this component
- Since:
- 1.6
- See Also:
-
getDropLocation
Returns the location that this component should visually indicate as the drop location during a DnD operation over the component, ornullif no location is to currently be shown.This method is not meant for querying the drop location from a
TransferHandler, as the drop location is only set after theTransferHandler'scanImporthas returned and has allowed for the location to be shown.When this property changes, a property change event with name "dropLocation" is fired by the component.
- Returns:
- the drop location
- Since:
- 1.6
- See Also:
-
setAutoCreateRowSorter
@BeanProperty(preferred=true, description="Whether or not to turn on sorting by default.") public void setAutoCreateRowSorter(boolean autoCreateRowSorter) Specifies whether aRowSortershould be created for the table whenever its model changes.When
setAutoCreateRowSorter(true)is invoked, aTableRowSorteris immediately created and installed on the table. While theautoCreateRowSorterproperty remainstrue, every time the model is changed, a newTableRowSorteris created and set as the table's row sorter. The default value for theautoCreateRowSorterproperty isfalse.- Parameters:
autoCreateRowSorter- whether or not aRowSortershould be automatically created- Since:
- 1.6
- See Also:
-
getAutoCreateRowSorter
public boolean getAutoCreateRowSorter()Returnstrueif whenever the model changes, a newRowSortershould be created and installed as the table's sorter; otherwise, returnsfalse.- Returns:
- true if a
RowSortershould be created when the model changes - Since:
- 1.6
-
setUpdateSelectionOnSort
@BeanProperty(expert=true, description="Whether or not to update the selection on sorting") public void setUpdateSelectionOnSort(boolean update) Specifies whether the selection should be updated after sorting. If true, on sorting the selection is reset such that the same rows, in terms of the model, remain selected. The default is true.- Parameters:
update- whether or not to update the selection on sorting- Since:
- 1.6
-
getUpdateSelectionOnSort
public boolean getUpdateSelectionOnSort()Returns true if the selection should be updated after sorting.- Returns:
- whether to update the selection on a sort
- Since:
- 1.6
-
setRowSorter
@BeanProperty(description="The table's RowSorter") public void setRowSorter(RowSorter<? extends TableModel> sorter) Sets theRowSorter.RowSorteris used to provide sorting and filtering to aJTable.This method clears the selection and resets any variable row heights.
This method fires a
PropertyChangeEventwhen appropriate, with the property name"rowSorter". For backward-compatibility, this method fires an additional event with the property name"sorter".If the underlying model of the
RowSorterdiffers from that of thisJTableundefined behavior will result.- Parameters:
sorter- theRowSorter;nullturns sorting off- Since:
- 1.6
- See Also:
-
getRowSorter
Returns the object responsible for sorting.- Returns:
- the object responsible for sorting
- Since:
- 1.6
-
setSelectionMode
@BeanProperty(enumerationValues={"ListSelectionModel.SINGLE_SELECTION","ListSelectionModel.SINGLE_INTERVAL_SELECTION","ListSelectionModel.MULTIPLE_INTERVAL_SELECTION"}, description="The selection mode used by the row and column selection models.") public void setSelectionMode(int selectionMode) Sets the table's selection mode to allow only single selections, a single contiguous interval, or multiple intervals.Note:
JTableprovides all the methods for handling column and row selection. When setting states, such assetSelectionMode, it not only updates the mode for the row selection model but also sets similar values in the selection model of thecolumnModel. 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
JTabledefault to using aDefaultListSelectionModelso thatJTableworks the same way as theJList. See thesetSelectionModemethod inJListfor details about the modes.- Parameters:
selectionMode- the mode used by the row and column selection models- See Also:
-
setRowSelectionAllowed
@BeanProperty(visualUpdate=true, description="If true, an entire row is selected for each selected cell.") public void setRowSelectionAllowed(boolean rowSelectionAllowed) Sets whether the rows in this model can be selected.- Parameters:
rowSelectionAllowed- true if this model will allow row selection- See Also:
-
getRowSelectionAllowed
public boolean getRowSelectionAllowed()Returns true if rows can be selected.- Returns:
- true if rows can be selected, otherwise false
- See Also:
-
setColumnSelectionAllowed
@BeanProperty(visualUpdate=true, description="If true, an entire column is selected for each selected cell.") public void setColumnSelectionAllowed(boolean columnSelectionAllowed) Sets whether the columns in this model can be selected.- Parameters:
columnSelectionAllowed- true if this model will allow column selection- See Also:
-
getColumnSelectionAllowed
public boolean getColumnSelectionAllowed()Returns true if columns can be selected.- Returns:
- true if columns can be selected, otherwise false
- See Also:
-
setCellSelectionEnabled
@BeanProperty(visualUpdate=true, description="Select a rectangular region of cells rather than rows or columns.") public void setCellSelectionEnabled(boolean cellSelectionEnabled) Sets whether this table allows both a column selection and a row selection to exist simultaneously. When set, the table treats the intersection of the row and column selection models as the selected cells. OverrideisCellSelectedto change this default behavior. This method is equivalent to setting both therowSelectionAllowedproperty andcolumnSelectionAllowedproperty of thecolumnModelto the supplied value.- Parameters:
cellSelectionEnabled- true if simultaneous row and column selection is allowed- See Also:
-
getCellSelectionEnabled
public boolean getCellSelectionEnabled()Returns true if both row and column selection models are enabled. Equivalent togetRowSelectionAllowed() && getColumnSelectionAllowed().- Returns:
- true if both row and column selection models are enabled
- See Also:
-
selectAll
public void selectAll()Selects all rows, columns, and cells in the table. -
clearSelection
public void clearSelection()Deselects all selected columns and rows. -
setRowSelectionInterval
public void setRowSelectionInterval(int index0, int index1) Selects the rows fromindex0toindex1, inclusive.- Parameters:
index0- one end of the intervalindex1- the other end of the interval- Throws:
IllegalArgumentException- ifindex0orindex1lie outside [0,getRowCount()-1]
-
setColumnSelectionInterval
public void setColumnSelectionInterval(int index0, int index1) Selects the columns fromindex0toindex1, inclusive.- Parameters:
index0- one end of the intervalindex1- the other end of the interval- Throws:
IllegalArgumentException- ifindex0orindex1lie outside [0,getColumnCount()-1]
-
addRowSelectionInterval
public void addRowSelectionInterval(int index0, int index1) Adds the rows fromindex0toindex1, inclusive, to the current selection.- Parameters:
index0- one end of the intervalindex1- the other end of the interval- Throws:
IllegalArgumentException- ifindex0orindex1lie outside [0,getRowCount()-1]
-
addColumnSelectionInterval
public void addColumnSelectionInterval(int index0, int index1) Adds the columns fromindex0toindex1, inclusive, to the current selection.- Parameters:
index0- one end of the intervalindex1- the other end of the interval- Throws:
IllegalArgumentException- ifindex0orindex1lie outside [0,getColumnCount()-1]
-
removeRowSelectionInterval
public void removeRowSelectionInterval(int index0, int index1) Deselects the rows fromindex0toindex1, inclusive.- Parameters:
index0- one end of the intervalindex1- the other end of the interval- Throws:
IllegalArgumentException- ifindex0orindex1lie outside [0,getRowCount()-1]
-
removeColumnSelectionInterval
public void removeColumnSelectionInterval(int index0, int index1) Deselects the columns fromindex0toindex1, inclusive.- Parameters:
index0- one end of the intervalindex1- the other end of the interval- Throws:
IllegalArgumentException- ifindex0orindex1lie outside [0,getColumnCount()-1]
-
getSelectedRow
Returns the index of the first selected row, -1 if no row is selected.- Returns:
- the index of the first selected row
-
getSelectedColumn
Returns the index of the first selected column, -1 if no column is selected.- Returns:
- the index of the first selected column
-
getSelectedRows
Returns the indices of all selected rows.- Returns:
- an array of integers containing the indices of all selected rows, or an empty array if no row is selected
- See Also:
-
getSelectedColumns
Returns the indices of all selected columns.- Returns:
- an array of integers containing the indices of all selected columns, or an empty array if no column is selected
- See Also:
-
getSelectedRowCount
Returns the number of selected rows.- Returns:
- the number of selected rows, 0 if no rows are selected
-
getSelectedColumnCount
Returns the number of selected columns.- Returns:
- the number of selected columns, 0 if no columns are selected
-
isRowSelected
public 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.- Parameters:
row- a row in the row model- Returns:
- true if
rowis a valid index and the row at that index is selected (where 0 is the first row)
-
isColumnSelected
public 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.- Parameters:
column- the column in the column model- Returns:
- true if
columnis a valid index and the column at that index is selected (where 0 is the first column)
-
isCellSelected
public 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.- Parameters:
row- the row being queriedcolumn- the column being queried- Returns:
- true if
rowandcolumnare valid indices and the cell at index(row, column)is selected, where the first row and first column are at index 0
-
changeSelection
public 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:toggleandextend. Most 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. Some UIs may need more functionality than this method provides, such as when manipulating the lead for discontiguous selection, and may not call into this method for some selection changes.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 from the anchor to the specified cell, clearing all other selections. -
toggle: true,extend: false. If the specified cell is selected, deselect it. If it is not selected, select it. -
toggle: true,extend: true. Apply the selection state of the anchor to all cells between it and the specified cell.
- Parameters:
rowIndex- affects the selection atrowcolumnIndex- affects the selection atcolumntoggle- see description aboveextend- if true, extend the current selection- Since:
- 1.3
-
-
getSelectionForeground
Returns the foreground color for selected cells.- Returns:
- the
Colorobject for the foreground property - See Also:
-
setSelectionForeground
@BeanProperty(description="A default foreground color for selected cells.") public void setSelectionForeground(Color selectionForeground) Sets the foreground color for selected cells. Cell renderers can use this color to render text and graphics for selected cells.The default value of this property is defined by the look and feel implementation.
This is a JavaBeans bound property.
- Parameters:
selectionForeground- theColorto use in the foreground for selected list items- See Also:
-
getSelectionBackground
Returns the background color for selected cells.- Returns:
- the
Colorused for the background of selected list items - See Also:
-
setSelectionBackground
@BeanProperty(description="A default background color for selected cells.") public void setSelectionBackground(Color selectionBackground) Sets the background color for selected cells. Cell renderers can use this color to the fill selected cells.The default value of this property is defined by the look and feel implementation.
This is a JavaBeans bound property.
- Parameters:
selectionBackground- theColorto use for the background of selected cells- See Also:
-
getColumn
Returns theTableColumnobject for the column in the table whose identifier is equal toidentifier, when compared usingequals.- Parameters:
identifier- the identifier object- Returns:
- the
TableColumnobject that matches the identifier - Throws:
IllegalArgumentException- ifidentifierisnullor noTableColumnhas this identifier
-
convertColumnIndexToModel
public int convertColumnIndexToModel(int viewColumnIndex) Maps the index of the column in the view atviewColumnIndexto the index of the column in the table model. Returns the index of the corresponding column in the model. IfviewColumnIndexis less than zero, returnsviewColumnIndex.- Parameters:
viewColumnIndex- the index of the column in the view- Returns:
- the index of the corresponding column in the model
- See Also:
-
convertColumnIndexToView
public int convertColumnIndexToView(int modelColumnIndex) Maps the index of the column in the table model atmodelColumnIndexto 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. IfmodelColumnIndexis less than zero, returnsmodelColumnIndex.- Parameters:
modelColumnIndex- the index of the column in the model- Returns:
- the index of the corresponding column in the view
- See Also:
-
convertRowIndexToView
public int convertRowIndexToView(int modelRowIndex) Maps the index of the row in terms of theTableModelto the view. If the contents of the model are not sorted the model and view indices are the same.- Parameters:
modelRowIndex- the index of the row in terms of the model- Returns:
- the index of the corresponding row in the view, or -1 if the row isn't visible
- Throws:
IndexOutOfBoundsException- if sorting is enabled and passed an index outside the number of rows of theTableModel- Since:
- 1.6
- See Also:
-
convertRowIndexToModel
public int convertRowIndexToModel(int viewRowIndex) Maps the index of the row in terms of the view to the underlyingTableModel. If the contents of the model are not sorted the model and view indices are the same.- Parameters:
viewRowIndex- the index of the row in the view- Returns:
- the index of the corresponding row in the model
- Throws:
IndexOutOfBoundsException- if sorting is enabled and passed an index outside the range of theJTableas determined by the methodgetRowCount- Since:
- 1.6
- See Also:
-
getRowCount
Returns the number of rows that can be shown in theJTable, given unlimited space. If aRowSorterwith a filter has been specified, the number of rows returned may differ from that of the underlyingTableModel.- Returns:
- the number of rows shown in the
JTable - See Also:
-
getColumnCount
Returns the number of columns in the column model. Note that this may be different from the number of columns in the table model.- Returns:
- the number of columns in the table
- See Also:
-
getColumnName
Returns the name of the column appearing in the view at column positioncolumn.- Parameters:
column- the column in the view being queried- Returns:
- the name of the column at position
columnin the view where the first column is column 0
-
getColumnClass
Returns the type of the column appearing in the view at column positioncolumn.- Parameters:
column- the column in the view being queried- Returns:
- the type of the column at position
columnin the view where the first column is column 0
-
getValueAt
Returns the cell value atrowandcolumn.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.- Parameters:
row- the row whose value is to be queriedcolumn- the column whose value is to be queried- Returns:
- the Object at the specified cell
-
setValueAt
Sets the value for the cell in the table model atrowandcolumn.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.aValueis the new value.- Parameters:
aValue- the new valuerow- the row of the cell to be changedcolumn- the column of the cell to be changed- See Also:
-
isCellEditable
public boolean isCellEditable(int row, int column) Returns true if the cell atrowandcolumnis editable. Otherwise, invokingsetValueAton 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.- Parameters:
row- the row whose value is to be queriedcolumn- the column whose value is to be queried- Returns:
- true if the cell is editable
- See Also:
-
addColumn
AppendsaColumnto the end of the array of columns held by thisJTable's column model. If the column name ofaColumnisnull, sets the column name ofaColumnto the name returned bygetModel().getColumnName().To add a column to this
JTableto display themodelColumn'th column of data in the model with a givenwidth,cellRenderer, andcellEditoryou can use:addColumn(new TableColumn(modelColumn, width, cellRenderer, cellEditor));[Any of theTableColumnconstructors can be used instead of this one.] The model column number is stored inside theTableColumnand 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.- Parameters:
aColumn- theTableColumnto be added- See Also:
-
removeColumn
RemovesaColumnfrom thisJTable's array of columns. Note: this method does not remove the column of data from the model; it just removes theTableColumnthat was responsible for displaying it.- Parameters:
aColumn- theTableColumnto be removed- See Also:
-
moveColumn
public void moveColumn(int column, int targetColumn) Moves the columncolumnto the position currently occupied by the columntargetColumnin the view. The old column attargetColumnis shifted left or right to make room.- Parameters:
column- the index of column to be movedtargetColumn- the new index of the column
-
columnAtPoint
Returns the index of the column thatpointlies in, or -1 if the result is not in the range [0,getColumnCount()-1].- Parameters:
point- the location of interest- Returns:
- the index of the column that
pointlies in, or -1 if the result is not in the range [0,getColumnCount()-1] - See Also:
-
rowAtPoint
Returns the index of the row thatpointlies in, or -1 if the result is not in the range [0,getRowCount()-1].- Parameters:
point- the location of interest- Returns:
- the index of the row that
pointlies in, or -1 if the result is not in the range [0,getRowCount()-1] - See Also:
-
getCellRect
Returns a rectangle for the cell that lies at the intersection ofrowandcolumn. IfincludeSpacingis 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
yandheightvalues set appropriately and thexandwidthvalues 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
includeSpacingparameter is ignored.- Parameters:
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; theconvertColumnIndexToView(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 models- Returns:
- the rectangle containing the cell at location
row,column - See Also:
-
doLayout
public void doLayout()Causes this table to lay out its rows and columns. Overridden so that columns can be resized to accommodate a change in the size of a containing parent. Resizes one or more of the columns in the table so that the total width of all of thisJTable's columns is equal to the width of the table.Before the layout begins the method gets the
resizingColumnof thetableHeader. When the method is called as a result of the resizing of an enclosing window, theresizingColumnisnull. This means that resizing has taken place "outside" theJTableand the change - or "delta" - should be distributed to all of the columns regardless of thisJTable's automatic resize mode.If the
resizingColumnis notnull, 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:
- AUTO_RESIZE_OFF: Don't automatically adjust the column's
widths at all. Use a horizontal scrollbar to accommodate the
columns when their sum exceeds the width of the
Viewport. If theJTableis not enclosed in aJScrollPanethis may leave parts of the table invisible. - AUTO_RESIZE_NEXT_COLUMN: Use just the column after the resizing column. This results in the "boundary" or divider between adjacent cells being independently adjustable.
- AUTO_RESIZE_SUBSEQUENT_COLUMNS: Use all columns after the one being adjusted to absorb the changes. This is the default behavior.
- AUTO_RESIZE_LAST_COLUMN: Automatically adjust the size of the last column only. If the bounds of the last column prevent the desired size from being allocated, set the width of the last column to the appropriate limit and make no further adjustments.
- AUTO_RESIZE_ALL_COLUMNS: Spread the delta amongst all the columns
in the
JTable, including the one that is being adjusted.
Note: When a
JTablemakes 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 theJTabledoes 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 theJTable's bounds. These respectively, result in the clipping of some columns or an area being painted in theJTable's background color during painting.The mechanism for distributing the delta amongst the available columns is provided in a private method in the
JTableclass:adjustSizes(long targetSize, final Resizable3 r, boolean inverse)
an explanation of which is provided in the following section.Resizable3is 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.Distributing the delta
Overview
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).
Definition
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 accommodation of the required space, DELTA.
Details
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 the MAX and MIN bounds are hit
When
targetSizeis outside the [MIN, MAX] range, the algorithm sets all sizes to their appropriate limiting value (maximum or minimum). - AUTO_RESIZE_OFF: Don't automatically adjust the column's
widths at all. Use a horizontal scrollbar to accommodate the
columns when their sum exceeds the width of the
-
sizeColumnsToFit
Deprecated.As of Swing version 1.0.3, replaced bydoLayout().Sizes the table columns to fit the available space.- Parameters:
lastColumnOnly- determines whether to resize last column only- See Also:
-
sizeColumnsToFit
public void sizeColumnsToFit(int resizingColumn) Obsolete as of Java 2 platform v1.4. Please use thedoLayout()method instead.- Parameters:
resizingColumn- the column whose resizing made this adjustment necessary or -1 if there is no such column- See Also:
-
getToolTipText
OverridesJComponent'sgetToolTipTextmethod in order to allow the renderer's tips to be used if it has text set.Note: For
JTableto properly display tooltips of its renderersJTablemust be a registered component with theToolTipManager. This is done automatically ininitializeLocalVars, but if at a later pointJTableis toldsetToolTipText(null)it will unregister the table component, and no tips from renderers will display anymore.- Overrides:
getToolTipTextin classJComponent- Parameters:
event- theMouseEventthat initiated theToolTipdisplay- Returns:
- a string containing the tooltip
- See Also:
-
setSurrendersFocusOnKeystroke
public void setSurrendersFocusOnKeystroke(boolean surrendersFocusOnKeystroke) Sets whether editors in this JTable get the keyboard focus when an editor is activated as a result of the JTable forwarding keyboard events for a cell. By default, this property is false, and the JTable retains the focus unless the cell is clicked.- Parameters:
surrendersFocusOnKeystroke- true if the editor should get the focus when keystrokes cause the editor to be activated- Since:
- 1.4
- See Also:
-
getSurrendersFocusOnKeystroke
public boolean getSurrendersFocusOnKeystroke()Returns true if the editor should get the focus when keystrokes cause the editor to be activated- Returns:
- true if the editor should get the focus when keystrokes cause the editor to be activated
- Since:
- 1.4
- See Also:
-
editCellAt
public boolean editCellAt(int row, int column) Programmatically starts editing the cell atrowandcolumn, if those indices are in the valid range, and the cell at those indices is editable. Note that this is a convenience method foreditCellAt(int, int, null).- Parameters:
row- the row to be editedcolumn- the column to be edited- Returns:
- false if for any reason the cell cannot be edited, or if the indices are invalid
-
editCellAt
Programmatically starts editing the cell atrowandcolumn, if those indices are in the valid range, and the cell at those indices is editable. To prevent theJTablefrom editing a particular table, column or cell value, return false from theisCellEditablemethod in theTableModelinterface.- Parameters:
row- the row to be editedcolumn- the column to be editede- event to pass intoshouldSelectCell; note that as of Java 2 platform v1.2, the call toshouldSelectCellis no longer made- Returns:
- false if for any reason the cell cannot be edited, or if the indices are invalid
-
isEditing
Returns true if a cell is being edited.- Returns:
- true if the table is editing a cell
- See Also:
-
getEditorComponent
Returns the component that is handling the editing session. If nothing is being edited, returns null.- Returns:
- Component handling editing session
-
getEditingColumn
public int getEditingColumn()Returns the index of the column that contains the cell currently being edited. If nothing is being edited, returns -1.- Returns:
- the index of the column that contains the cell currently being edited; returns -1 if nothing being edited
- See Also:
-
getEditingRow
public int getEditingRow()Returns the index of the row that contains the cell currently being edited. If nothing is being edited, returns -1.- Returns:
- the index of the row that contains the cell currently being edited; returns -1 if nothing being edited
- See Also:
-
getUI
Returns the L&F object that renders this component.- Overrides:
getUIin classJComponent- Returns:
- the
TableUIobject that renders this component
-
setUI
@BeanProperty(hidden=true, visualUpdate=true, description="The UI object that implements the Component's LookAndFeel.") public void setUI(TableUI ui) Sets the L&F object that renders this component and repaints.- Parameters:
ui- the TableUI L&F object- See Also:
-
updateUI
public void updateUI()Notification from theUIManagerthat the L&F has changed. Replaces the current UI object with the latest version from theUIManager.- Overrides:
updateUIin classJComponent- See Also:
-
getUIClassID
Returns the suffix used to construct the name of the L&F class used to render this component.- Overrides:
getUIClassIDin classJComponent- Returns:
- the string "TableUI"
- See Also:
-
setModel
@BeanProperty(description="The model that is the source of the data for this view.") public void setModel(TableModel dataModel) Sets the data model for this table todataModeland registers with it for listener notifications from the new data model.- Parameters:
dataModel- the new data source for this table- Throws:
IllegalArgumentException- ifdataModelisnull- See Also:
-
getModel
Returns theTableModelthat provides the data displayed by thisJTable.- Returns:
- the
TableModelthat provides the data displayed by thisJTable - See Also:
-
setColumnModel
@BeanProperty(description="The object governing the way columns appear in the view.") public void setColumnModel(TableColumnModel columnModel) Sets the column model for this table tocolumnModeland registers for listener notifications from the new column model. Also sets the column model of theJTableHeadertocolumnModel.- Parameters:
columnModel- the new data source for this table- Throws:
IllegalArgumentException- ifcolumnModelisnull- See Also:
-
getColumnModel
Returns theTableColumnModelthat contains all column information of this table.- Returns:
- the object that provides the column state of the table
- See Also:
-
setSelectionModel
@BeanProperty(description="The selection model for rows.") public void setSelectionModel(ListSelectionModel selectionModel) Sets the row selection model for this table toselectionModeland registers for listener notifications from the new selection model.- Parameters:
selectionModel- the new selection model- Throws:
IllegalArgumentException- ifselectionModelisnull- See Also:
-
getSelectionModel
Returns theListSelectionModelthat is used to maintain row selection state.- Returns:
- the object that provides row selection state,
nullif row selection is not allowed - See Also:
-
sorterChanged
RowSorterListenernotification that theRowSorterhas changed in some way.- Specified by:
sorterChangedin interfaceRowSorterListener- Parameters:
e- theRowSorterEventdescribing the change- Throws:
NullPointerException- ifeisnull- Since:
- 1.6
-
tableChanged
Invoked when this table'sTableModelgenerates aTableModelEvent. TheTableModelEventshould be constructed in the coordinate system of the model; the appropriate mapping to the view coordinate system is performed by thisJTablewhen 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.
- Specified by:
tableChangedin interfaceTableModelListener- Parameters:
e- aTableModelEventto notify listener that a table model has changed
-
columnAdded
Invoked when a column is added to the table column model.Application code will not use these methods explicitly, they are used internally by JTable.
- Specified by:
columnAddedin interfaceTableColumnModelListener- Parameters:
e- aTableColumnModelEvent- See Also:
-
columnRemoved
Invoked when a column is removed from the table column model.Application code will not use these methods explicitly, they are used internally by JTable.
- Specified by:
columnRemovedin interfaceTableColumnModelListener- Parameters:
e- aTableColumnModelEvent- See Also:
-
columnMoved
Invoked when a column is repositioned. If a cell is being edited, then editing is stopped and the cell is redrawn.Application code will not use these methods explicitly, they are used internally by JTable.
- Specified by:
columnMovedin interfaceTableColumnModelListener- Parameters:
e- the event received- See Also:
-
columnMarginChanged
Invoked when a column is moved due to a margin change. If a cell is being edited, then editing is stopped and the cell is redrawn.Application code will not use these methods explicitly, they are used internally by JTable.
- Specified by:
columnMarginChangedin interfaceTableColumnModelListener- Parameters:
e- the event received- See Also:
-
columnSelectionChanged
Invoked when the selection model of theTableColumnModelis changed.Application code will not use these methods explicitly, they are used internally by JTable.
- Specified by:
columnSelectionChangedin interfaceTableColumnModelListener- Parameters:
e- the event received- See Also:
-
valueChanged
Invoked when the row selection changes -- repaints to show the new selection.Application code will not use these methods explicitly, they are used internally by JTable.
- Specified by:
valueChangedin interfaceListSelectionListener- Parameters:
e- the event received- See Also:
-
editingStopped
Invoked when editing is finished. The changes are saved and the editor is discarded.Application code will not use these methods explicitly, they are used internally by JTable.
- Specified by:
editingStoppedin interfaceCellEditorListener- Parameters:
e- the event received- See Also:
-
editingCanceled
Invoked when editing is canceled. The editor object is discarded and the cell is rendered once again.Application code will not use these methods explicitly, they are used internally by JTable.
- Specified by:
editingCanceledin interfaceCellEditorListener- Parameters:
e- the event received- See Also:
-
setPreferredScrollableViewportSize
@BeanProperty(bound=false, description="The preferred size of the viewport.") public void setPreferredScrollableViewportSize(Dimension size) Sets the preferred size of the viewport for this table.- Parameters:
size- aDimensionobject specifying thepreferredSizeof aJViewportwhose view is this table- See Also:
-
getPreferredScrollableViewportSize
Returns the preferred size of the viewport for this table.- Specified by:
getPreferredScrollableViewportSizein interfaceScrollable- Returns:
- a
Dimensionobject containing thepreferredSizeof theJViewportwhich displays this table - See Also:
-
getScrollableUnitIncrement
Returns the scroll increment (in pixels) that completely exposes one new row or column (depending on the orientation).This method is called each time the user requests a unit scroll.
- Specified by:
getScrollableUnitIncrementin interfaceScrollable- Parameters:
visibleRect- the view area visible within the viewportorientation- eitherSwingConstants.VERTICALorSwingConstants.HORIZONTALdirection- less than zero to scroll up/left, greater than zero for down/right- Returns:
- the "unit" increment for scrolling in the specified direction
- See Also:
-
getScrollableBlockIncrement
ReturnsvisibleRect.heightorvisibleRect.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.- Specified by:
getScrollableBlockIncrementin interfaceScrollable- Parameters:
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/right.- Returns:
visibleRect.heightorvisibleRect.widthper the orientation- See Also:
-
getScrollableTracksViewportWidth
Returns false ifautoResizeModeis set toAUTO_RESIZE_OFF, which indicates that the width of the viewport does not determine the width of the table. Otherwise returns true.- Specified by:
getScrollableTracksViewportWidthin interfaceScrollable- Returns:
- false if
autoResizeModeis set toAUTO_RESIZE_OFF, otherwise returns true - See Also:
-
getScrollableTracksViewportHeight
Returnsfalseto indicate that the height of the viewport does not determine the height of the table, unlessgetFillsViewportHeightistrueand the preferred height of the table is smaller than the viewport's height.- Specified by:
getScrollableTracksViewportHeightin interfaceScrollable- Returns:
falseunlessgetFillsViewportHeightistrueand the table needs to be stretched to fill the viewport- See Also:
-
setFillsViewportHeight
@BeanProperty(description="Whether or not this table is always made large enough to fill the height of an enclosing viewport") public void setFillsViewportHeight(boolean fillsViewportHeight) Sets whether or not this table is always made large enough to fill the height of an enclosing viewport. If the preferred height of the table is smaller than the viewport, then the table will be stretched to fill the viewport. In other words, this ensures the table is never smaller than the viewport. The default for this property isfalse.- Parameters:
fillsViewportHeight- whether or not this table is always made large enough to fill the height of an enclosing viewport- Since:
- 1.6
- See Also:
-
getFillsViewportHeight
public boolean getFillsViewportHeight()Returns whether or not this table is always made large enough to fill the height of an enclosing viewport.- Returns:
- whether or not this table is always made large enough to fill the height of an enclosing viewport
- Since:
- 1.6
- See Also:
-
createDefaultRenderers
protected void createDefaultRenderers()Creates default cell renderers for objects, numbers, doubles, dates, booleans, and icons.- See Also:
-
createDefaultEditors
protected void createDefaultEditors()Creates default cell editors for objects, numbers, and boolean values.- See Also:
-
initializeLocalVars
protected void initializeLocalVars()Initializes table properties to their default values. -
createDefaultDataModel
Returns the default table model object, which is aDefaultTableModel. A subclass can override this method to return a different table model object.- Returns:
- the default table model object
- See Also:
-
createDefaultColumnModel
Returns the default column model object, which is aDefaultTableColumnModel. A subclass can override this method to return a different column model object.- Returns:
- the default column model object
- See Also:
-
createDefaultSelectionModel
Returns the default selection model object, which is aDefaultListSelectionModel. A subclass can override this method to return a different selection model object.- Returns:
- the default selection model object
- See Also:
-
createDefaultTableHeader
Returns the default table header object, which is aJTableHeader. A subclass can override this method to return a different table header object.- Returns:
- the default table header object
- See Also:
-
resizeAndRepaint
protected void resizeAndRepaint()Equivalent torevalidatefollowed byrepaint. -
getCellEditor
Returns the active cell editor, which isnullif the table is not currently editing.- Returns:
- the
TableCellEditorthat does the editing, ornullif the table is not currently editing. - See Also:
-
setCellEditor
@BeanProperty(description="The table's active cell editor.") public void setCellEditor(TableCellEditor anEditor) Sets the active cell editor.- Parameters:
anEditor- the active cell editor- See Also:
-
setEditingColumn
public void setEditingColumn(int aColumn) Sets theeditingColumnvariable.- Parameters:
aColumn- the column of the cell to be edited- See Also:
-
setEditingRow
public void setEditingRow(int aRow) Sets theeditingRowvariable.- Parameters:
aRow- the row of the cell to be edited- See Also:
-
getCellRenderer
Returns an appropriate renderer for the cell specified by this row and column. If theTableColumnfor this column has a non-null renderer, returns that. If not, finds the class of the data in this column (usinggetColumnClass) 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.
- Parameters:
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 column- Returns:
- the assigned renderer; if
nullreturns the default renderer for this type of object - See Also:
-
prepareRenderer
Prepares the renderer by querying the data model for the value and selection state of the cell atrow,column. Returns the component (may be aComponentor aJComponent) under the event location.During a printing operation, this method will configure the renderer without indicating selection or focus, to prevent them from appearing in the printed output. To do other customizations based on whether or not the table is being printed, you can check the value of
JComponent.isPaintingForPrint(), either here or within custom renderers.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.
- Parameters:
renderer- theTableCellRendererto 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 column- Returns:
- the
Componentunder the event location
-
getCellEditor
Returns an appropriate editor for the cell specified byrowandcolumn. If theTableColumnfor this column has a non-null editor, returns that. If not, finds the class of the data in this column (usinggetColumnClass) 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.
- Parameters:
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 column- Returns:
- the editor for this cell;
if
nullreturn the default editor for this type of cell - See Also:
-
prepareEditor
Prepares the editor by querying the data model for the value and selection state of the cell atrow,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.
- Parameters:
editor- theTableCellEditorto 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 column- Returns:
- the
Componentbeing edited
-
removeEditor
public void removeEditor()Discards the editor object and frees the real estate it used for cell rendering. -
paramString
Returns a string representation of this table. This method is intended to be used only for debugging purposes, and the content and format of the returned string may vary between implementations. The returned string may be empty but may not benull.- Overrides:
paramStringin classJComponent- Returns:
- a string representation of this table
-
print
A convenience method that displays a printing dialog, and then prints thisJTablein modePrintMode.FIT_WIDTH, with no header or footer text. A modal progress dialog, with an abort option, will be shown for the duration of printing.Note: In headless mode, no dialogs are shown and printing occurs on the default printer.
- Returns:
- true, unless printing is cancelled by the user
- Throws:
PrinterException- if an error in the print system causes the job to be aborted- Since:
- 1.5
- See Also:
-
print
A convenience method that displays a printing dialog, and then prints thisJTablein the given printing mode, with no header or footer text. A modal progress dialog, with an abort option, will be shown for the duration of printing.Note: In headless mode, no dialogs are shown and printing occurs on the default printer.
- Parameters:
printMode- the printing mode that the printable should use- Returns:
- true, unless printing is cancelled by the user
- Throws:
PrinterException- if an error in the print system causes the job to be aborted- Since:
- 1.5
- See Also:
-
print
public boolean print(JTable.PrintMode printMode, MessageFormat headerFormat, MessageFormat footerFormat) throws PrinterException A convenience method that displays a printing dialog, and then prints thisJTablein the given printing mode, with the specified header and footer text. A modal progress dialog, with an abort option, will be shown for the duration of printing.Note: In headless mode, no dialogs are shown and printing occurs on the default printer.
- Parameters:
printMode- the printing mode that the printable should useheaderFormat- aMessageFormatspecifying the text to be used in printing a header, or null for nonefooterFormat- aMessageFormatspecifying the text to be used in printing a footer, or null for none- Returns:
- true, unless printing is cancelled by the user
- Throws:
PrinterException- if an error in the print system causes the job to be aborted- Since:
- 1.5
- See Also:
-
print
public boolean print(JTable.PrintMode printMode, MessageFormat headerFormat, MessageFormat footerFormat, boolean showPrintDialog, PrintRequestAttributeSet attr, boolean interactive) throws PrinterException, HeadlessException Prints this table, as specified by the fully featuredprintmethod, with the default printer specified as the print service.- Parameters:
printMode- the printing mode that the printable should useheaderFormat- aMessageFormatspecifying the text to be used in printing a header, ornullfor nonefooterFormat- aMessageFormatspecifying the text to be used in printing a footer, ornullfor noneshowPrintDialog- whether or not to display a print dialogattr- aPrintRequestAttributeSetspecifying any printing attributes, ornullfor noneinteractive- whether or not to print in an interactive mode- Returns:
- true, unless printing is cancelled by the user
- Throws:
HeadlessException- if the method is asked to show a printing dialog or run interactively, andGraphicsEnvironment.isHeadlessreturnstruePrinterException- if an error in the print system causes the job to be aborted- Since:
- 1.5
- See Also:
-
print
public boolean print(JTable.PrintMode printMode, MessageFormat headerFormat, MessageFormat footerFormat, boolean showPrintDialog, PrintRequestAttributeSet attr, boolean interactive, PrintService service) throws PrinterException, HeadlessException Prints thisJTable. Takes steps that the majority of developers would take in order to print aJTable. In short, it prepares the table, callsgetPrintableto fetch an appropriatePrintable, and then sends it to the printer.A
booleanparameter allows you to specify whether or not a printing dialog is displayed to the user. When it is, the user may use the dialog to change the destination printer or printing attributes, or even to cancel the print. Another two parameters allow for aPrintServiceand printing attributes to be specified. These parameters can be used either to provide initial values for the print dialog, or to specify values when the dialog is not shown.A second
booleanparameter allows you to specify whether or not to perform printing in an interactive mode. Iftrue, a modal progress dialog, with an abort option, is displayed for the duration of printing . This dialog also prevents any user action which may affect the table. However, it can not prevent the table from being modified by code (for example, another thread that posts updates usingSwingUtilities.invokeLater). It is therefore the responsibility of the developer to ensure that no other code modifies the table in any way during printing (invalid modifications include changes in: size, renderers, or underlying data). Printing behavior is undefined when the table is changed during printing.If
falseis specified for this parameter, no dialog will be displayed and printing will begin immediately on the event-dispatch thread. This blocks any other events, including repaints, from being processed until printing is complete. Although this effectively prevents the table from being changed, it doesn't provide a good user experience. For this reason, specifyingfalseis only recommended when printing from an application with no visible GUI.Note: Attempting to show the printing dialog or run interactively, while in headless mode, will result in a
HeadlessException.Before fetching the printable, this method will gracefully terminate editing, if necessary, to prevent an editor from showing in the printed result. Additionally,
JTablewill prepare its renderers during printing such that selection and focus are not indicated. As far as customizing further how the table looks in the printout, developers can provide custom renderers or paint code that conditionalize on the value ofJComponent.isPaintingForPrint().See
getPrintable(JTable.PrintMode, MessageFormat, MessageFormat)for more description on how the table is printed.- Parameters:
printMode- the printing mode that the printable should useheaderFormat- aMessageFormatspecifying the text to be used in printing a header, ornullfor nonefooterFormat- aMessageFormatspecifying the text to be used in printing a footer, ornullfor noneshowPrintDialog- whether or not to display a print dialogattr- aPrintRequestAttributeSetspecifying any printing attributes, ornullfor noneinteractive- whether or not to print in an interactive modeservice- the destinationPrintService, ornullto use the default printer- Returns:
- true, unless printing is cancelled by the user
- Throws:
HeadlessException- if the method is asked to show a printing dialog or run interactively, andGraphicsEnvironment.isHeadlessreturnstruePrinterException- if an error in the print system causes the job to be aborted- Since:
- 1.6
- See Also:
-
getPrintable
public Printable getPrintable(JTable.PrintMode printMode, MessageFormat headerFormat, MessageFormat footerFormat) Return aPrintablefor use in printing this JTable.This method is meant for those wishing to customize the default
Printableimplementation used byJTable'sprintmethods. Developers wanting simply to print the table should use one of those methods directly.The
Printablecan be requested in one of two printing modes. In both modes, it spreads table rows naturally in sequence across multiple pages, fitting as many rows as possible per page.PrintMode.NORMALspecifies that the table be printed at its current size. In this mode, there may be a need to spread columns across pages in a similar manner to that of the rows. When the need arises, columns are distributed in an order consistent with the table'sComponentOrientation.PrintMode.FIT_WIDTHspecifies that the output be scaled smaller, if necessary, to fit the table's entire width (and thereby all columns) on each page. Width and height are scaled equally, maintaining the aspect ratio of the output.The
Printableheads the portion of table on each page with the appropriate section from the table'sJTableHeader, if it has one.Header and footer text can be added to the output by providing
MessageFormatarguments. The printing code requests Strings from the formats, providing a single item which may be included in the formatted string: anIntegerrepresenting the current page number.You are encouraged to read the documentation for
MessageFormatas some characters, such as single-quote, are special and need to be escaped.Here's an example of creating a
MessageFormatthat can be used to print "Duke's Table: Page - " and the current page number:// notice the escaping of the single quote // notice how the page number is included with "{0}" MessageFormat format = new MessageFormat("Duke''s Table: Page - {0}");The
Printableconstrains what it draws to the printable area of each page that it prints. Under certain circumstances, it may find it impossible to fit all of a page's content into that area. In these cases the output may be clipped, but the implementation makes an effort to do something reasonable. Here are a few situations where this is known to occur, and how they may be handled by this particular implementation:- In any mode, when the header or footer text is too wide to fit
completely in the printable area -- print as much of the text as
possible starting from the beginning, as determined by the table's
ComponentOrientation. - In any mode, when a row is too tall to fit in the printable area -- print the upper-most portion of the row and paint no lower border on the table.
- In
PrintMode.NORMALwhen a column is too wide to fit in the printable area -- print the center portion of the column and leave the left and right borders off the table.
It is entirely valid for this
Printableto be wrapped inside another in order to create complex reports and documents. You may even request that different pages be rendered into different sized printable areas. The implementation must be prepared to handle this (possibly by doing its layout calculations on the fly). However, providing different heights to each page will likely not work well withPrintMode.NORMALwhen it has to spread columns across pages.As far as customizing how the table looks in the printed result,
JTableitself will take care of hiding the selection and focus during printing. For additional customizations, your renderers or painting code can customize the look based on the value ofJComponent.isPaintingForPrint()Also, before calling this method you may wish to first modify the state of the table, such as to cancel cell editing or have the user size the table appropriately. However, you must not modify the state of the table after this
Printablehas been fetched (invalid modifications include changes in size or underlying data). The behavior of the returnedPrintableis undefined once the table has been changed.- Parameters:
printMode- the printing mode that the printable should useheaderFormat- aMessageFormatspecifying the text to be used in printing a header, or null for nonefooterFormat- aMessageFormatspecifying the text to be used in printing a footer, or null for none- Returns:
- a
Printablefor printing this JTable - Since:
- 1.5
- See Also:
- In any mode, when the header or footer text is too wide to fit
completely in the printable area -- print as much of the text as
possible starting from the beginning, as determined by the table's
-
getAccessibleContext
Gets the AccessibleContext associated with this JTable. For tables, the AccessibleContext takes the form of an AccessibleJTable. A new AccessibleJTable instance is created if necessary.- Specified by:
getAccessibleContextin interfaceAccessible- Overrides:
getAccessibleContextin classComponent- Returns:
- an AccessibleJTable that serves as the AccessibleContext of this JTable
-
new JScrollPane(aTable).