is new.
java.lang.Objectjava.awt.Component
java.awt.Container
javax.swing.JComponent
javax.swing.JTable
,
RowSorterListener
,
TableColumnModelListener
,
TableModelListener
,
Scrollable
public class JTable
,
RowSorterListenerThe JTable is used to display and edit regular two-dimensional tables of cells. See How to Use Tables in The Java Tutorial for task-oriented documentation and examples of using JTable.
The JTable has many facilities that make it possible to customize its rendering and editing but provides defaults for these features so that simple tables can be set up easily. For example, to set up a table with 10 rows and 10 columns of numbers:
TableModel dataModel = new AbstractTableModel() {
public int getColumnCount() { return 10; }
public int getRowCount() { return 10;}
public Object getValueAt(int row, int col) { return new Integer(row*col); }
};
JTable table = new JTable(dataModel);
JScrollPane scrollpane = new JScrollPane(table);
Note that if you wish to use a JTable in a standalone view (outside of a JScrollPane) and want the header displayed, you can get it using getTableHeader() and display it separately.
When designing applications that use the JTable it is worth paying close attention to the data structures that will represent the table's data. The DefaultTableModel is a model implementation that uses a Vector of 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 J2SE 5 adds methods to JTable to provide convenient access to some common printing needs. Simple new print() methods allow for quick and easy addition of printing support to your application. In addition, a new getPrintable(javax.swing.JTable.PrintMode, java.text.MessageFormat, java.text.MessageFormat) method is available for more advanced printing needs.
As for all JComponent classes, you can use InputMap and ActionMap to associate an Action object with a KeyStroke and execute the action under specified conditions.
Warning: 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 TM has been added to the java.beans package. Please see XMLEncoder.
See Also:
DefaultTableModel
,
TableRowSorter| Nested Class Summary | |
|---|---|
| protected class | JTable.AccessibleJTable This class implements accessibility support for the JTable class. |
static class | JTable.DropLocation A subclass of TransferHandler.DropLocation representing a drop location for a JTable. |
| static class | JTable.PrintMode Printing modes, used in printing JTables. |
| Nested classes/interfaces inherited from class javax.swing.JComponent |
|---|
| JComponent.AccessibleJComponent |
| Nested classes/interfaces inherited from class java.awt.Container |
|---|
| Container.AccessibleAWTContainer |
| Nested classes/interfaces inherited from class java.awt.Component |
|---|
Component.AccessibleAWTComponent, Component.BaselineResizeBehavior , Component.BltBufferStrategy, Component.FlipBufferStrategy |
| Field Summary | |
|---|---|
| static int | AUTO_RESIZE_ALL_COLUMNS During all resize operations, proportionately resize all columns. |
| static int | AUTO_RESIZE_LAST_COLUMN During all resize operations, apply adjustments to the last column only. |
| static int | AUTO_RESIZE_NEXT_COLUMN When a column is adjusted in the UI, adjust the next column the opposite way. |
| static int | AUTO_RESIZE_OFF Do not adjust column widths automatically; use a scrollbar. |
| static int | AUTO_RESIZE_SUBSEQUENT_COLUMNS During UI adjustment, change subsequent columns to preserve the total width; this is the default behavior. |
| protected boolean | autoCreateColumnsFromModel The table will query the TableModel to build the default set of columns if this is true. |
| protected int | autoResizeMode Determines if the table automatically resizes the width of the table's columns to take up the entire width of the table, and how it does the resizing. |
| protected TableCellEditor | cellEditor The object that overwrites the screen real estate occupied by the current cell and allows the user to change its contents. |
| protected boolean | cellSelectionEnabled Obsolete as of Java 2 platform v1.3. |
| protected TableColumnModel | columnModel The TableColumnModel of the table. |
| protected TableModel | dataModel The TableModel of the table. |
| protected Hashtable | defaultEditorsByColumnClass A table of objects that display and edit the contents of a cell, indexed by class as declared in getColumnClass in the TableModel interface. |
| protected Hashtable | defaultRenderersByColumnClass A table of objects that display the contents of a cell, indexed by class as declared in getColumnClass in the TableModel interface. |
| protected int | editingColumn Identifies the column of the cell being edited. |
| protected int | editingRow Identifies the row of the cell being edited. |
| protected Component | editorComp If editing, the Component that is handling the editing. |
| protected Color | gridColor The color of the grid. |
| protected Dimension | preferredViewportSize Used by the Scrollable interface to determine the initial visible area. |
| protected int | rowHeight The height in pixels of each row in the table. |
| protected int | rowMargin The height in pixels of the margin between the cells in each row. |
| protected boolean | rowSelectionAllowed True if row selection is allowed in this table. |
| protected Color | selectionBackground The background color of selected cells. |
| protected Color | selectionForeground The foreground color of selected cells. |
| protected ListSelectionModel | selectionModel The ListSelectionModel of the table, used to keep track of row selections. |
| protected boolean | showHorizontalLines The table draws horizontal lines between cells if showHorizontalLines is true. |
| protected boolean | showVerticalLines The table draws vertical lines between cells if showVerticalLines is true. |
| protected JTableHeader | tableHeader The TableHeader working with the table. |
| Fields inherited from class javax.swing.JComponent |
|---|
| accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW |
| Fields inherited from class java.awt.Component |
|---|
| BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT |
| Fields inherited from interface java.awt.image.ImageObserver |
|---|
| ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH |
| Constructor Summary | |
|---|---|
| JTable() Constructs a default JTable that is initialized with a default data model, a default column model, and a default selection model. | |
| JTable(int numRows, int numColumns) Constructs a JTable with numRows and numColumns of empty cells using DefaultTableModel. | |
| JTable(Object[][] rowData, Object[] columnNames) Constructs a JTable to display the values in the two dimensional array, rowData, with column names, columnNames. | |
| JTable(TableModel dm) Constructs a JTable that is initialized with dm as the data model, a default column model, and a default selection model. | |
| JTable(TableModel dm, TableColumnModel cm) Constructs a JTable that is initialized with dm as the data model, cm as the column model, and a default selection model. | |
| JTable(TableModel dm, TableColumnModel cm, ListSelectionModel sm) Constructs a JTable that is initialized with dm as the data model, cm as the column model, and sm as the selection model. | |
| JTable(Vector rowData, Vector columnNames) Constructs a JTable to display the values in the Vector of Vectors, rowData, with column names, columnNames. | |
| Method Summary | |
|---|---|
| void | addColumn(TableColumn aColumn) Appends aColumn to the end of the array of columns held by this JTable's column model. |
| void | addColumnSelectionInterval(int index0, int index1) Adds the columns from index0 to index1, inclusive, to the current selection. |
| void | addNotify() Calls the configureEnclosingScrollPane method. |
| void | addRowSelectionInterval(int index0, int index1) Adds the rows from index0 to index1, inclusive, to the current selection. |
| void | changeSelection(int rowIndex, int columnIndex, boolean toggle, boolean extend) Updates the selection models of the table, depending on the state of the two flags: toggle and extend. |
| void | clearSelection() Deselects all selected columns and rows. |
| void | columnAdded(TableColumnModelEvent e) Invoked when a column is added to the table column model. |
| int | columnAtPoint(Point point) Returns the index of the column that point lies in, or -1 if the result is not in the range [0, getColumnCount()-1]. |
| void | columnMarginChanged(ChangeEvent e) Invoked when a column is moved due to a margin change. |
| void | columnMoved(TableColumnModelEvent e) Invoked when a column is repositioned. |
| void | columnRemoved(TableColumnModelEvent e) Invoked when a column is removed from the table column model. |
| void | columnSelectionChanged(ListSelectionEvent e) Invoked when the selection model of the TableColumnModel is changed. |
| protected void | configureEnclosingScrollPane() If this JTable is the viewportView of an enclosing JScrollPane (the usual situation), configure this ScrollPane by, amongst other things, installing the table's tableHeader as the columnHeaderView of the scroll pane. |
| int | convertColumnIndexToModel(int viewColumnIndex) Maps the index of the column in the view at viewColumnIndex to the index of the column in the table model. |
| int | convertColumnIndexToView(int modelColumnIndex) Maps the index of the column in the table model at modelColumnIndex to the index of the column in the view. |
int | convertRowIndexToModel (int viewRowIndex) Maps the index of the row in terms of the view to the underlying TableModel. |
int | convertRowIndexToView (int modelRowIndex) Maps the index of the row in terms of the TableModel to the view. |
| protected TableColumnModel | createDefaultColumnModel() Returns the default column model object, which is a DefaultTableColumnModel. |
| void | createDefaultColumnsFromModel() Creates default columns for the table from the data model using the getColumnCount method defined in the TableModel interface. |
| protected TableModel | createDefaultDataModel() Returns the default table model object, which is a DefaultTableModel. |
| protected void | createDefaultEditors() Creates default cell editors for objects, numbers, and boolean values. |
| protected void | createDefaultRenderers() Creates default cell renderers for objects, numbers, doubles, dates, booleans, and icons. |
| protected ListSelectionModel | createDefaultSelectionModel() Returns the default selection model object, which is a DefaultListSelectionModel. |
| protected JTableHeader | createDefaultTableHeader() Returns the default table header object, which is a JTableHeader. |
| static JScrollPane | createScrollPaneForTable(JTable aTable) Deprecated. As of Swing version 1.0.2, replaced by new JScrollPane(aTable). |
| void | doLayout() Causes this table to lay out its rows and columns. |
| boolean | editCellAt(int row, int column) Programmatically starts editing the cell at row and column, if those indices are in the valid range, and the cell at those indices is editable. |
| boolean | editCellAt(int row, int column, EventObject e) Programmatically starts editing the cell at row and column, if those indices are in the valid range, and the cell at those indices is editable. |
| void | editingCanceled(ChangeEvent e) Invoked when editing is canceled. |
| void | editingStopped(ChangeEvent e) Invoked when editing is finished. |
| AccessibleContext | getAccessibleContext() Gets the AccessibleContext associated with this JTable. |
| boolean | getAutoCreateColumnsFromModel() Determines whether the table will create default columns from the model. |
| int | getAutoResizeMode() Returns the auto resize mode of the table. |
| TableCellEditor | getCellEditor() Returns the cell editor. |
| TableCellEditor | getCellEditor(int row, int column) Returns an appropriate editor for the cell specified by row and column. |
| Rectangle | getCellRect(int row, int column, boolean includeSpacing) Returns a rectangle for the cell that lies at the intersection of row and column. |
| TableCellRenderer | getCellRenderer(int row, int column) Returns an appropriate renderer for the cell specified by this row and column. |
| boolean | getCellSelectionEnabled() Returns true if both row and column selection models are enabled. |
| TableColumn | getColumn(Object identifier) Returns the TableColumn object for the column in the table whose identifier is equal to identifier, when compared using equals. |
| Class<?> | getColumnClass(int column) Returns the type of the column appearing in the view at column position column. |
| int | getColumnCount() Returns the number of columns in the column model. |
| TableColumnModel | getColumnModel() Returns the TableColumnModel that contains all column information of this table. |
| String | getColumnName(int column) Returns the name of the column appearing in the view at column position column. |
| boolean | getColumnSelectionAllowed() Returns true if columns can be selected. |
| TableCellEditor | getDefaultEditor(Class<?> columnClass) Returns the editor to be used when no editor has been set in a TableColumn. |
| TableCellRenderer | getDefaultRenderer(Class<?> columnClass) Returns the cell renderer to be used when no renderer has been set in a TableColumn. |
| boolean | getDragEnabled() Gets the value of the dragEnabled property. |
JTable.DropLocation | getDropLocation () Returns the location that this component should visually indicate as the drop location during a DnD operation over the component. |
DropMode | getDropMode () Returns the drop mode for this component. |
| int | getEditingColumn() Returns the index of the column that contains the cell currently being edited. |
| int | getEditingRow() Returns the index of the row that contains the cell currently being edited. |
| Component | getEditorComponent() Returns the component that is handling the editing session. |
boolean | getFillsViewportHeight () Returns whether or not this table is always made large enough to fill the height of an enclosing viewport. |
| Color | getGridColor() Returns the color used to draw grid lines. |
| Dimension | getIntercellSpacing() Returns the horizontal and vertical space between cells. |
| TableModel | getModel() Returns the TableModel that provides the data displayed by this JTable. |
| Dimension | getPreferredScrollableViewportSize() Returns the preferred size of the viewport for this table. |
| Printable | getPrintable(JTable.PrintMode printMode, MessageFormat headerFormat, MessageFormat footerFormat) Return a Printable for use in printing this JTable. |
| int | getRowCount() Returns the number of rows that can be shown in the JTable, given unlimited space. ![]() |
| int | getRowHeight() Returns the height of a table row, in pixels. |
| int | getRowHeight(int row) Returns the height, in pixels, of the cells in row. |
| int | getRowMargin() Gets the amount of empty space, in pixels, between cells. |
| boolean | getRowSelectionAllowed() Returns true if rows can be selected. |
RowSorter <? extends TableModel | getRowSorter () Returns the object responsible for sorting. |
| int | getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) Returns visibleRect.height or visibleRect.width, depending on this table's orientation. |
| boolean | getScrollableTracksViewportHeight() Returns false to indicate that the height of the viewport does not determine the height of the table, unless getFillsViewportHeight is true and the preferred height of the table is smaller than the viewport's height. ![]() |
| boolean | getScrollableTracksViewportWidth() Returns false if autoResizeMode is set to AUTO_RESIZE_OFF, which indicates that the width of the viewport does not determine the width of the table. |
| int | getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) Returns the scroll increment (in pixels) that completely exposes one new row or column (depending on the orientation). |
| int | getSelectedColumn() Returns the index of the first selected column, -1 if no column is selected. |
| int | getSelectedColumnCount() Returns the number of selected columns. |
| int[] | getSelectedColumns() Returns the indices of all selected columns. |
| int | getSelectedRow() Returns the index of the first selected row, -1 if no row is selected. |
| int | getSelectedRowCount() Returns the number of selected rows. |
| int[] | getSelectedRows() Returns the indices of all selected rows. |
| Color | getSelectionBackground() Returns the background color for selected cells. |
| Color | getSelectionForeground() Returns the foreground color for selected cells. |
| ListSelectionModel | getSelectionModel() Returns the ListSelectionModel that is used to maintain row selection state. |
| boolean | getShowHorizontalLines() Returns true if the table draws horizontal lines between cells, false if it doesn't. |
| boolean | getShowVerticalLines() Returns true if the table draws vertical lines between cells, false if it doesn't. |
| boolean | getSurrendersFocusOnKeystroke() Returns true if the editor should get the focus when keystrokes cause the editor to be activated |
| JTableHeader | getTableHeader() Returns the tableHeader used by this JTable. |
| String | getToolTipText(MouseEvent event) Overrides JComponent's getToolTipText method in order to allow the renderer's tips to be used if it has text set. |
| TableUI | getUI() Returns the L&F object that renders this component. |
| String | getUIClassID() Returns the suffix used to construct the name of the L&F class used to render this component. |
boolean | getUpdateSelectionOnSort () Returns true if the selection should be updated after sorting. |
| Object | getValueAt(int row, int column) Returns the cell value at row and column. |
| protected void | initializeLocalVars() Initializes table properties to their default values. |
| boolean | isCellEditable(int row, int column) Returns true if the cell at row and column is editable. |
| boolean | isCellSelected(int row, int column) Returns true if the specified indices are in the valid range of rows and columns and the cell at the specified position is selected. |
| boolean | isColumnSelected(int column) Returns true if the specified index is in the valid range of columns, and the column at that index is selected. |
| boolean | isEditing() Returns true if a cell is being edited. |
| boolean | isRowSelected(int row) Returns true if the specified index is in the valid range of rows, and the row at that index is selected. |
| void | moveColumn(int column, int targetColumn) Moves the column column to the position currently occupied by the column targetColumn in the view. |
| protected String | paramString() Returns a string representation of this table. |
| Component | prepareEditor(TableCellEditor editor, int row, int column) Prepares the editor by querying the data model for the value and selection state of the cell at row, column. |
| Component | prepareRenderer(TableCellRenderer renderer, int row, int column) Prepares the renderer by querying the data model for the value and selection state of the cell at row, column. |
| boolean | print() A convenience method that displays a printing dialog, and then prints this JTable in mode PrintMode.FIT_WIDTH, with no header or footer text. |
| boolean | print(JTable.PrintMode printMode) A convenience method that displays a printing dialog, and then prints this JTable in the given printing mode, with no header or footer text. |
| boolean | print(JTable.PrintMode printMode, MessageFormat headerFormat, MessageFormat footerFormat) A convenience method that displays a printing dialog, and then prints this JTable in the given printing mode, with the specified header and footer text. |
| boolean | print( JTable.PrintMode printMode, MessageFormat headerFormat, MessageFormat footerFormat, boolean showPrintDialog, PrintRequestAttributeSet Prints ![]() table, as specified by the fully featured print![]() |
boolean | print ( JTable.PrintMode printMode, MessageFormat headerFormat, MessageFormat footerFormat, boolean showPrintDialog, PrintRequestAttributeSet attr, boolean interactive, PrintService Prints this JTable. |
| protected boolean | processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) Invoked to process the key bindings for ks as the result of the KeyEvent e. |
| void | removeColumn(TableColumn aColumn) Removes aColumn from this JTable's array of columns. |
| void | removeColumnSelectionInterval(int index0, int index1) Deselects the columns from index0 to index1, inclusive. |
| void | removeEditor() Discards the editor object and frees the real estate it used for cell rendering. |
| void | removeNotify() Calls the unconfigureEnclosingScrollPane method. |
| void | removeRowSelectionInterval(int index0, int index1) Deselects the rows from index0 to index1, inclusive. |
| protected void | resizeAndRepaint() Equivalent to revalidate followed by repaint. |
| int | rowAtPoint(Point point) Returns the index of the row that point lies in, or -1 if the result is not in the range [0, getRowCount()-1]. |
| void | selectAll() Selects all rows, columns, and cells in the table. |
| void | setAutoCreateColumnsFromModel(boolean autoCreateColumnsFromModel) Sets this table's autoCreateColumnsFromModel flag. |
| void | setAutoResizeMode(int mode) Sets the table's auto resize mode when the table is resized. |
| void | setCellEditor(TableCellEditor anEditor) Sets the cellEditor variable. |
| void | setCellSelectionEnabled(boolean cellSelectionEnabled) Sets whether this table allows both a column selection and a row selection to exist simultaneously. |
| void | setColumnModel(TableColumnModel columnModel) Sets the column model for this table to newModel and registers for listener notifications from the new column model. |
| void | setColumnSelectionAllowed(boolean columnSelectionAllowed) Sets whether the columns in this model can be selected. |
| void | setColumnSelectionInterval(int index0, int index1) Selects the columns from index0 to index1, inclusive. |
| void | setDefaultEditor(Class<?> columnClass, TableCellEditor editor) Sets a default cell editor to be used if no editor has been set in a TableColumn. |
| void | setDefaultRenderer(Class<?> columnClass, TableCellRenderer renderer) Sets a default cell renderer to be used if no renderer has been set in a TableColumn. |
| void | setDragEnabled(boolean b) Sets the dragEnabled property, which must be true to enable automatic drag handling (the first part of drag and drop) on this component. |
void | setDropMode ( DropMode Set the drop mode for this component. |
| void | setEditingColumn(int aColumn) Sets the editingColumn variable. |
| void | setEditingRow(int aRow) Sets the editingRow variable. |
void | setFillsViewportHeight (boolean fillsViewportHeight) Sets whether or not this table is always made large enough to fill the height of an enclosing viewport. |
| void | setGridColor(Color gridColor) Sets the color used to draw grid lines to gridColor and redisplays. |
| void | setIntercellSpacing(Dimension intercellSpacing) Sets the rowMargin and the columnMargin -- the height and width of the space between cells -- to intercellSpacing. |
| void | setModel(TableModel dataModel) Sets the data model for this table to newModel and registers with it for listener notifications from the new data model. |
| void | setPreferredScrollableViewportSize(Dimension size) Sets the preferred size of the viewport for this table. |
| void | setRowHeight(int rowHeight) Sets the height, in pixels, of all cells to rowHeight, revalidates, and repaints. |
| void | setRowHeight(int row, int rowHeight) Sets the height for row to rowHeight, revalidates, and repaints. |
| void | setRowMargin(int rowMargin) Sets the amount of empty space between cells in adjacent rows. |
| void | setRowSelectionAllowed(boolean rowSelectionAllowed) Sets whether the rows in this model can be selected. |
| void | setRowSelectionInterval(int index0, int index1) Selects the rows from index0 to index1, inclusive. |
void | setRowSorter ( RowSorter <? extends TableModel Sets the RowSorter. |
| void | setSelectionBackground(Color selectionBackground) Sets the background color for selected cells. |
| void | setSelectionForeground(Color selectionForeground) Sets the foreground color for selected cells. |
| void | setSelectionMode(int selectionMode) Sets the table's selection mode to allow only single selections, a single contiguous interval, or multiple intervals. |
| void | setSelectionModel(ListSelectionModel newModel) Sets the row selection model for this table to newModel and registers for listener notifications from the new selection model. |
| void | setShowGrid(boolean showGrid) Sets whether the table draws grid lines around cells. |
| void | setShowHorizontalLines(boolean showHorizontalLines) Sets whether the table draws horizontal lines between cells. |
| void | setShowVerticalLines(boolean showVerticalLines) Sets whether the table draws vertical lines between cells. |
| 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. |
| void | setTableHeader(JTableHeader tableHeader) Sets the tableHeader working with this JTable to newHeader. |
| void | setUI(TableUI ui) Sets the L&F object that renders this component and repaints. |
void | setUpdateSelectionOnSort (boolean update) Specifies whether the selection should be updated after sorting. |
| void | setValueAt(Object aValue, int row, int column) Sets the value for the cell in the table model at row and column. |
| void | sizeColumnsToFit(boolean lastColumnOnly) Deprecated. As of Swing version 1.0.3, replaced by doLayout(). |
| void | sizeColumnsToFit(int resizingColumn) Obsolete as of Java 2 platform v1.4. |
void | sorterChanged ( RowSorterEvent RowSorterListener notification that the RowSorter has changed in some way. |
| void | tableChanged(TableModelEvent e) Invoked when this table's TableModel generates a TableModelEvent. |
| protected void | unconfigureEnclosingScrollPane() Reverses the effect of configureEnclosingScrollPane by replacing the columnHeaderView of the enclosing scroll pane with null. |
| void | updateUI() Notification from the UIManager that the L&F has changed. |
| void | valueChanged(ListSelectionEvent e) Invoked when the row selection changes -- repaints to show the new selection. |
| Methods inherited from class java.lang.Object |
|---|
| clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Field Detail |
|---|
public static final int AUTO_RESIZE_OFF
public static final int AUTO_RESIZE_NEXT_COLUMN
public static final int AUTO_RESIZE_SUBSEQUENT_COLUMNS
public static final int AUTO_RESIZE_LAST_COLUMN
public static final int AUTO_RESIZE_ALL_COLUMNS
protected TableModel dataModel
protected TableColumnModel columnModel
protected ListSelectionModel selectionModel
protected JTableHeader tableHeader
protected int rowHeight
protected int rowMargin
protected Color gridColor
protected boolean showHorizontalLines
protected boolean showVerticalLines
protected int autoResizeMode
protected boolean autoCreateColumnsFromModel
protected Dimension preferredViewportSize
protected boolean rowSelectionAllowed
protected boolean cellSelectionEnabled
protected transient Component editorComp
protected transient TableCellEditor cellEditor
protected transient int editingColumn
protected transient int editingRow
protected transient Hashtable defaultRenderersByColumnClass
protected transient Hashtable defaultEditorsByColumnClass
protected Color selectionForeground
protected Color selectionBackground
| Constructor Detail |
|---|
public JTable()
public JTable(TableModel dm)
public JTable(TableModel dm,
TableColumnModel cm)
public JTable(TableModel dm,
TableColumnModel cm,
ListSelectionModel sm)
public JTable(int numRows,
int numColumns)
public JTable(Vector rowData,
Vector columnNames)
((Vector)rowData.elementAt(1)).elementAt(5);
public JTable(Object[][] rowData,
Object[] columnNames)
rowData[1][5];
All rows must be of the same length as columnNames.
| Method Detail |
|---|
public void addNotify()
protected void configureEnclosingScrollPane()
public void removeNotify()
protected void unconfigureEnclosingScrollPane()
@Deprecated public static JScrollPane createScrollPaneForTable(JTable aTable)
public void setTableHeader(JTableHeader tableHeader)
public JTableHeader getTableHeader()
public void setRowHeight(int rowHeight)
public int getRowHeight()
public void setRowHeight(int row,
int rowHeight)
public int getRowHeight(int row)
public void setRowMargin(int rowMargin)
public int getRowMargin()
public void setIntercellSpacing(Dimension intercellSpacing)
public Dimension getIntercellSpacing()
public void setGridColor(Color gridColor)
public Color getGridColor()
public void setShowGrid(boolean showGrid)
public void setShowHorizontalLines(boolean showHorizontalLines)
public void setShowVerticalLines(boolean showVerticalLines)
public boolean getShowHorizontalLines()
public boolean getShowVerticalLines()
public void setAutoResizeMode(int mode)
public int getAutoResizeMode()
public void setAutoCreateColumnsFromModel(boolean autoCreateColumnsFromModel)
public boolean getAutoCreateColumnsFromModel()
public void createDefaultColumnsFromModel()
Clears any existing columns before creating the new columns based on information from the model.
public void setDefaultRenderer(Class<?> columnClass,
TableCellRenderer renderer)
public TableCellRenderer getDefaultRenderer(Class<?> columnClass)
public void setDefaultEditor(Class<?> columnClass,
TableCellEditor editor)
public TableCellEditor getDefaultEditor(Class<?> columnClass)
public void setDragEnabled(boolean b)
When automatic drag handling is enabled, most look and feels 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 to true can therefore have a subtle effect on how selections behave.
Some look and feels might not support automatic drag and drop; they will ignore this property. You can work around such look and feels by modifying the component to directly call the exportAsDrag method of a TransferHandler.
public boolean getDragEnabled()
setDropMode
public final void
setDropMode
(
DropMode
dropMode)
Set the drop mode for this component. For backward compatibility, the default for this property is DropMode.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.
JTable supports the following drop modes:
DropMode.USE_SELECTION
DropMode.ON
DropMode.INSERT
DropMode.INSERT_ROWS
DropMode.INSERT_COLS
DropMode.ON_OR_INSERT
DropMode.ON_OR_INSERT_ROWS
DropMode.ON_OR_INSERT_COLS
The drop mode is only meaningful if this component has a TransferHandler that accepts drops.
Parameters:
dropMode - the drop mode to use
Throws:
IllegalArgumentException
- if the drop mode is unsupported or null
Since:
1.6
See Also:
getDropMode()
,
getDropLocation()
,
JComponent.setTransferHandler(javax.swing.TransferHandler)
,
TransferHandler
getDropMode
public final
DropMode
getDropMode
()
Returns the drop mode for this component.
Returns:
the drop mode for this component
Since:
1.6
See Also:
setDropMode(javax.swing.DropMode)
getDropLocation
public final
JTable.DropLocation
getDropLocation
()
Returns the location that this component should visually indicate as the drop location during a DnD operation over the component. This will be null if there is no DnD operation over the component or if the component's TransferHandler has indicated that it cannot accept the current transfer (and has not specified that the drop location be indicated anyway).
This method is not meant for querying the drop location from a TransferHandler as the drop location is only set after the TransferHandler's canImport or shouldIndicateAnyway methods have returned true.
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:
setDropMode(javax.swing.DropMode)
,
TransferHandler.TransferInfo
,
TransferHandler.canImport(TransferHandler.TransferInfo)
, TransferHandler#shouldIndicateAnyway(TransferHandler.TransferInfo)
setUpdateSelectionOnSort
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
public void
setRowSorter
(
RowSorter
<? extends
TableModel
> sorter)
Sets the RowSorter. RowSorter is used to provide sorting and filtering to a JTable.
This method clears the selection and resets any variable row heights.
If the underlying model of the RowSorter differs from that of this JTable undefined behavior will result.
Parameters:
sorter - the RowSorter; null turns sorting off
Since:
1.6
See Also:
TableRowSorter
getRowSorter
public
RowSorter
<? extends
TableModel
>
getRowSorter
()
Returns the object responsible for sorting.
Returns:
the object responsible for sorting
Since:
1.6
public void setSelectionMode(int selectionMode)
Both the row and column selection models for JTable default to using a DefaultListSelectionModel so that JTable works the same way as the JList. See the setSelectionMode method in JList for details about the modes.
public void setRowSelectionAllowed(boolean rowSelectionAllowed)
public boolean getRowSelectionAllowed()
public void setColumnSelectionAllowed(boolean columnSelectionAllowed)
public boolean getColumnSelectionAllowed()
public void setCellSelectionEnabled(boolean cellSelectionEnabled)
public boolean getCellSelectionEnabled()
public void selectAll()
public void clearSelection()
public void setRowSelectionInterval(int index0,
int index1)
public void setColumnSelectionInterval(int index0,
int index1)
public void addRowSelectionInterval(int index0,
int index1)
public void addColumnSelectionInterval(int index0,
int index1)
public void removeRowSelectionInterval(int index0,
int index1)
public void removeColumnSelectionInterval(int index0,
int index1)
public int getSelectedRow()
public int getSelectedColumn()
public int[] getSelectedRows()
public int[] getSelectedColumns()
public int getSelectedRowCount()
public int getSelectedColumnCount()
public boolean isRowSelected(int row)
public boolean isColumnSelected(int column)
public boolean isCellSelected(int row,
int column)
public void changeSelection(int rowIndex,
int columnIndex,
boolean toggle,
boolean extend)
This implementation uses the following conventions:
Apply
of
all cells between it and
the specified
cell.
public Color getSelectionForeground()
public void setSelectionForeground(Color selectionForeground)
The default value of this property is defined by the look and feel implementation.
This is a JavaBeans bound property.
public Color getSelectionBackground()
public void setSelectionBackground(Color selectionBackground)
The default value of this property is defined by the look and feel implementation.
This is a JavaBeans bound property.
public TableColumn getColumn(Object identifier)
public int convertColumnIndexToModel(int viewColumnIndex)
public int convertColumnIndexToView(int modelColumnIndex)
convertRowIndexToView
public int
convertRowIndexToView
(int modelRowIndex)
Maps the index of the row in terms of the TableModel to 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 the TableModel
Since:
1.6
See Also:
TableRowSorter
convertRowIndexToModel
public int
convertRowIndexToModel
(int viewRowIndex)
Maps the index of the row in terms of the view to the underlying TableModel. 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 the JTable as determined by the method getRowCount
Since:
1.6
See Also:
TableRowSorter
,
getRowCount()
public int getRowCount()
Returns the number of rows that can be shown in the JTable, given unlimited space. If a RowSorter with a filter has been specified, the number of rows returned may differ from that of the underlying TableModel.
shown
in
the JTable
public int getColumnCount()
public String getColumnName(int column)
public Class<?> getColumnClass(int column)
public Object getValueAt(int row,
int column)
Note : The column is specified in the table view's display order, and not in the TableModel's column order. This is an important distinction because as the user rearranges the columns in the table, the column at a given index in the view will change. Meanwhile the user's actions never affect the model's column ordering.
public void setValueAt(Object aValue,
int row,
int column)
Note : The column is specified in the table view's display order, and not in the TableModel's column order. This is an important distinction because as the user rearranges the columns in the table, the column at a given index in the view will change. Meanwhile the user's actions never affect the model's column ordering. aValue is the new value.
public boolean isCellEditable(int row,
int column)
Note : The column is specified in the table view's display order, and not in the TableModel's column order. This is an important distinction because as the user rearranges the columns in the table, the column at a given index in the view will change. Meanwhile the user's actions never affect the model's column ordering.
public void addColumn(TableColumn aColumn)
To add a column to this JTable to display the modelColumn'th column of data in the model with a given width, cellRenderer, and cellEditor you can use:
addColumn(new TableColumn(modelColumn, width, cellRenderer, cellEditor));
[Any of the TableColumn constructors can be used instead of this one.] The model column number is stored inside the TableColumn and is used during rendering and editing to locate the appropriates data values in the model. The model column number does not change when columns are reordered in the view.
public void removeColumn(TableColumn aColumn)
public void moveColumn(int column,
int targetColumn)
public int columnAtPoint(Point point)
public int rowAtPoint(Point point)
public Rectangle getCellRect(int row,
int column,
boolean includeSpacing)
If the column index is valid but the row index is less than zero the method returns a rectangle with the y and height values set appropriately and the x and width values both set to zero. In general, when either the row or column indices indicate a cell outside the appropriate range, the method returns a rectangle depicting the closest edge of the closest cell that is within the table's range. When both row and column indices are out of range the returned rectangle covers the closest point of the closest cell.
In all cases, calculations that use this method to calculate results along one axis will not fail because of anomalies in calculations along the other axis. When the cell is not valid the includeSpacing parameter is ignored.
public void doLayout()
Before the layout begins the method gets the resizingColumn of the tableHeader. When the method is called as a result of the resizing of an enclosing window, the resizingColumn is null. This means that resizing has taken place "outside" the JTable and the change - or "delta" - should be distributed to all of the columns regardless of this JTable's automatic resize mode.
If the resizingColumn is not null, it is one of the columns in the table that has changed size rather than the table itself. In this case the auto-resize modes govern the way the extra (or deficit) space is distributed amongst the available columns.
The modes are:
The mechanism for distributing the delta amongst the available columns is provided in a private method in the JTable class:
adjustSizes(long targetSize, final Resizable3 r, boolean inverse)an explanation of which is provided in the following section. Resizable3 is a private interface that allows any data structure containing a collection of elements with a size, preferred size, maximum size and minimum size to have its elements manipulated by the algorithm.
Call "DELTA" the difference between the target size and the sum of the preferred sizes of the elements in r. The individual sizes are calculated by taking the original preferred sizes and adding a share of the DELTA - that share being based on how far each preferred size is from its limiting bound (minimum or maximum).
Call the individual constraints min[i], max[i], and pref[i].
Call their respective sums: MIN, MAX, and PREF.
Each new size will be calculated using:
size[i] = pref[i] + delta[i]
where each individual delta[i] is calculated according to: If (DELTA < 0) we are in shrink mode where:
DELTA
delta[i] = ------------ * (pref[i] - min[i])
(PREF - MIN)
If (DELTA > 0) we are in expand mode where:
DELTA
delta[i] = ------------ * (max[i] - pref[i])
(MAX - PREF)
The overall effect is that the total size moves that same percentage, k, towards the total minimum or maximum and that percentage guarantees accomodation of the required space, DELTA.
Naive evaluation of the formulae presented here would be subject to the aggregated rounding errors caused by doing this operation in finite precision (using ints). To deal with this, the multiplying factor above, is constantly recalculated and this takes account of the rounding errors in the previous iterations. The result is an algorithm that produces a set of integers whose values exactly sum to the supplied targetSize, and does so by spreading the rounding errors evenly over the given elements.
When targetSize is outside the [MIN, MAX] range, the algorithm sets all sizes to their appropriate limiting value (maximum or minimum).
@Deprecated public void sizeColumnsToFit(boolean lastColumnOnly)
public void sizeColumnsToFit(int resizingColumn)
public String getToolTipText(MouseEvent event)
public void setSurrendersFocusOnKeystroke(boolean surrendersFocusOnKeystroke)
public boolean getSurrendersFocusOnKeystroke()
public boolean editCellAt(int row,
int column)
public boolean editCellAt(int row,
int column,
EventObject e)
public boolean isEditing()
public Component getEditorComponent()
public int getEditingColumn()
public int getEditingRow()
public TableUI getUI()
public void setUI(TableUI ui)
public void updateUI()
public String getUIClassID()
public void setModel(TableModel dataModel)
public TableModel getModel()
public void setColumnModel(TableColumnModel columnModel)
public TableColumnModel getColumnModel()
public void setSelectionModel(ListSelectionModel newModel)
public ListSelectionModel getSelectionModel()
sorterChanged
public void
sorterChanged
(
RowSorterEvent
e)
RowSorterListener notification that the RowSorter has changed in some way.
Specified by:
sorterChanged
in interface
RowSorterListener
Parameters:
e - the RowSorterEvent describing the change
Throws:
NullPointerException
- if e is null
Since:
1.6
public void tableChanged(TableModelEvent e)
Application code will not use these methods explicitly, they are used internally by JTable.
Note that as of 1.3, this method clears the selection, if any.
public void columnAdded(TableColumnModelEvent e)
Application code will not use these methods explicitly, they are used internally by JTable.
public void columnRemoved(TableColumnModelEvent e)
Application code will not use these methods explicitly, they are used internally by JTable.
public void columnMoved(TableColumnModelEvent e)
Application code will not use these methods explicitly, they are used internally by JTable.
public void columnMarginChanged(ChangeEvent e)
Application code will not use these methods explicitly, they are used internally by JTable.
public void columnSelectionChanged(ListSelectionEvent e)
Application code will not use these methods explicitly, they are used internally by JTable.
public void valueChanged(ListSelectionEvent e)
Application code will not use these methods explicitly, they are used internally by JTable.
public void editingStopped(ChangeEvent e)
Application code will not use these methods explicitly, they are used internally by JTable.
public void editingCanceled(ChangeEvent e)
Application code will not use these methods explicitly, they are used internally by JTable.
public void setPreferredScrollableViewportSize(Dimension size)
public Dimension getPreferredScrollableViewportSize()
public int getScrollableUnitIncrement(Rectangle visibleRect,
int orientation,
int direction)
This method is called each time the user requests a unit scroll.
public int getScrollableBlockIncrement(Rectangle visibleRect,
int orientation,
int direction)
public boolean getScrollableTracksViewportWidth()
public boolean getScrollableTracksViewportHeight()
table, unless getFillsViewportHeight is true and the preferred height of the table is smaller than the viewport's height.
false unless getFillsViewportHeight is true and the table needs to be stretched to fill the viewport
,
setFillsViewportHeight(boolean)
,
getFillsViewportHeight()
setFillsViewportHeight
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 is false.
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()
,
getScrollableTracksViewportHeight()
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:
#setFillsViewportheight
protected boolean processKeyBinding(KeyStroke ks,
KeyEvent e,
int condition,
boolean pressed)
protected void createDefaultRenderers()
protected void createDefaultEditors()
protected void initializeLocalVars()
protected TableModel createDefaultDataModel()
protected TableColumnModel createDefaultColumnModel()
protected ListSelectionModel createDefaultSelectionModel()
protected JTableHeader createDefaultTableHeader()
protected void resizeAndRepaint()
public TableCellEditor getCellEditor()
public void setCellEditor(TableCellEditor anEditor)
public void setEditingColumn(int aColumn)
public void setEditingRow(int aRow)
public TableCellRenderer getCellRenderer(int row,
int column)
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.
public Component prepareRenderer(TableCellRenderer renderer,
int row,
int column)
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.
public TableCellEditor getCellEditor(int row,
int column)
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.
public Component prepareEditor(TableCellEditor editor,
int row,
int 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.
public void removeEditor()
protected String paramString()
public boolean print()
throws PrinterException
Note: In headless mode, no dialogs
are shown and printing occurs on the default printer.
will be shown.
SecurityException
- if this thread is not allowed to initiate a print job request
print(JTable.PrintMode, MessageFormat, MessageFormat, boolean, PrintRequestAttributeSet, boolean, PrintService)
public boolean print(JTable.PrintMode printMode)
throws PrinterException
Note: In headless mode, no dialogs
are shown and printing occurs on the default printer.
will be shown.
SecurityException
- if this thread is not allowed to initiate a print job request
print(JTable.PrintMode, MessageFormat, MessageFormat, boolean, PrintRequestAttributeSet, boolean, PrintService)
public boolean print(JTable.PrintMode printMode,
MessageFormat headerFormat,
MessageFormat footerFormat)
throws PrinterException
Note: In headless mode, no dialogs
are shown and printing occurs on the default printer.
will be shown.
SecurityException
- if this thread is not allowed to initiate a print job request
print(JTable.PrintMode, MessageFormat, MessageFormat, boolean, PrintRequestAttributeSet, boolean, PrintService)
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 featured
print
A boolean parameter 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 printing attributes or even cancel the print. Another parameter allows for printing attributes to be specified directly. This can be used either to provide the initial values for the print dialog, or to supply any needed attributes when the dialog is not shown.
A second boolean parameter allows you to specify whether or not to perform printing in an interactive mode. If true, 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 using SwingUtilities.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 false is 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, specifying false is 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 prepares the table in order to get the most desirable printed result. If the table is currently in an editing mode, it terminates the editing as gracefully as possible. It also ensures that the the table's current selection and focused cell are not indicated in the printed output. This is handled on the view level, and only for the duration of the printing, thus no notification needs to be sent to the selection models.
See
getPrintable(javax.swing.JTable.PrintMode, java.text.MessageFormat, java.text.MessageFormat)
method, with the default printer specified as the print service.
for further description on how the table is printed.
SecurityException
- if this thread is not allowed to initiate a print job request
PrinterException
- if an error in the print system causes the job to be aborted
print(JTable.PrintMode, MessageFormat, MessageFormat, boolean, PrintRequestAttributeSet, boolean, PrintService)
getPrintable(javax.swing.JTable.PrintMode, java.text.MessageFormat, java.text.MessageFormat)
print
public boolean
(
JTable.PrintMode
printMode,
MessageFormat
headerFormat,
MessageFormat
footerFormat, boolean showPrintDialog,
PrintRequestAttributeSet
attr, boolean interactive,
PrintService
service) throws
PrinterException
,
HeadlessException
Prints this JTable. Takes steps that the majority of developers would take in order to print a JTable. In short, it prepares the table, calls getPrintable to fetch an appropriate Printable, and then sends it to the printer.
A boolean parameter 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 a PrintService and 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 boolean parameter allows you to specify whether or not to perform printing in an interactive mode. If true, 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 using SwingUtilities.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 false is 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, specifying false is 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, JTable will 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 of
JComponent.isPaintingForPrint()
.
See
getPrintable(javax.swing.JTable.PrintMode, java.text.MessageFormat, java.text.MessageFormat)
for more description on how the table is printed.
Parameters:
printMode - the printing mode that the printable should use
headerFormat - a MessageFormat specifying the text to be used in printing a header, or null for none
footerFormat - a MessageFormat specifying the text to be used in printing a footer, or null for none
showPrintDialog - whether or not to display a print dialog
attr - a PrintRequestAttributeSet specifying any printing attributes, or null for none
interactive - whether or not to print in an interactive mode
service - the destination PrintService, or null to 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, and GraphicsEnvironment.isHeadless returns true
SecurityException
- if a security manager exists and its
SecurityManager.checkPrintJobAccess()
method disallows this thread from creating a print job request
PrinterException
- if an error in the print system causes the job to be aborted
Since:
1.6
See Also:
getPrintable(javax.swing.JTable.PrintMode, java.text.MessageFormat, java.text.MessageFormat)
,
GraphicsEnvironment.isHeadless()
public Printable getPrintable(JTable.PrintMode printMode,
MessageFormat headerFormat,
MessageFormat footerFormat)
This method is meant for those wishing to customize the default Printable implementation used by JTable's print methods. Developers wanting simply to print the table should use one of those methods directly.
The Printable can 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.NORMAL specifies 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's ComponentOrientation. PrintMode.FIT_WIDTH specifies 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 Printable heads the portion of table on each page with the appropriate section from the table's JTableHeader, if it has one.
Header and footer text can be added to the output by providing MessageFormat arguments. The printing code requests Strings from the formats, providing a single item which may be included in the formatted string: an Integer representing the current page number.
You are encouraged to read the documentation for MessageFormat as some characters, such as single-quote, are special and need to be escaped.
Here's an example of creating a MessageFormat that 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 Printable constrains 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:
It is entirely valid for this Printable to 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 with PrintMode.NORMAL when it has to spread columns across pages.
As far as customizing how the table looks in the printed result, JTable itself 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 of
JComponent.isPaintingForPrint()
Also,
It is important to note that this Printable prints the table at its current visual state, using the table's existing renderers.
before
Before
calling this
method
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
modify the state of the table (such as to change the renderers, cancel editing, or hide the selection).
You must not, however, modify the table in any way
after
this Printable
has been
is
fetched (invalid modifications include changes
in size
in: size, renderers,
or underlying data). The behavior of the returned Printable is undefined once the table has been changed.
Here's a simple example that calls this method to fetch a Printable, shows a cross-platform print dialog, and then prints the Printable unless the user cancels the dialog:
// prepare the table for printing here first (for example, hide selection) // wrap in a try/finally so table can be restored even if something fails try { // fetch the printable Printable printable = table.getPrintable(JTable.PrintMode.FIT_WIDTH, new MessageFormat("My Table"), new MessageFormat("Page - {0}")); // fetch a PrinterJob PrinterJob job = PrinterJob.getPrinterJob(); // set the Printable on the PrinterJob job.setPrintable(printable); // create an attribute set to store attributes from the print dialog PrintRequestAttributeSet attr = new HashPrintRequestAttributeSet(); // display a print dialog and record whether or not the user cancels it boolean printAccepted = job.printDialog(attr); // if the user didn't cancel the dialog if (printAccepted) { // do the printing (may need to handle PrinterException) job.print(attr); } } finally { // restore the original table state here (for example, restore selection) }
print(JTable.PrintMode, MessageFormat, MessageFormat, boolean, PrintRequestAttributeSet, boolean)
,
Printable
,
PrinterJob
public AccessibleContext getAccessibleContext()