JTable

JTable is a user-interface component that presents data in a two-dimensional table format. It 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.

Tables are composed of many parts. These include: TableModel, TableHeader, TableColumn, TableColumnModel, TableModelListener, TableCellRenderer, and TableCellEditor. The example demonstrates a minimal implementation. JTable has seven constructors. The most intuitive constructor expects an Object[][] parameter that represents the 2D data, and an Object[] parameter that contains the column names.

The user can change the width of columns by selecting the boundary between column headers and dragging it horizontally. The user can also reposition an entire column by selecting the column's header and dragging it horizontally to a new location.

The default behavior of a JTable provides a row selection capability. The line below allows individual cells to be selected and subsequently modified.

   table.setCellSelectionEnabled( true );
To receive notification of changes to the contents of individual cells, the programmer creates and registers a TableModelListener object. The TableModelEvent object "knows" the row and column of the affected cell, but the TableModel object must be messaged in order to retrieve the current value.

Somewhat less interesting is the ability to be notified that a row, column, or cell has been selected. JTable uses the same selection model as the JList component. Because you can select rows and columns independently of each other, a table actually has two selection models - one for row selections and another for column selections. The column selection model is owned and controlled by the TableColumnModel installed in the table, while the row selection model belongs to the table itself. Even though these models are separate, they are not quite independent of each other, because JTable has access to both of them and coordinates row and column selections via five selection policies. [Topley, p929]   These policies (or attributes) are configured by using the following methods:

The column headers will not work unless the table is embedded in a JScrollPane component.

[Reference: Topley, pp875-963]