Java Reference
In-Depth Information
columnModel.addColumn(firstColumn);
TableColumn secondColumn = new TableColumn(0);
secondColumn.setHeaderValue(headers[0]);
columnModel.addColumn(secondColumn);
JTable table = new JTable(model, columnModel);
public JTable(TableModel model, TableColumnModel columnModel,
ListSelectionModel selectionModel)
// Set single selection mode
ListSelectionModel selectionModel = new DefaultListSelectionModel();
selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JTable table = new JTable(model, columnModel, selectionModel);
The no-argument constructor creates a table with no rows and no columns. The second
constructor takes two integers to create an empty table with a set number of rows and columns.
■
Note
Table cells created from
JTable
constructors are editable, not read-only. To change their contents
in code, just call the
public void setValueAt(Object value, int row, int column)
method
of
JTable
.
The next two constructors are useful when your tabular data is already in a specially structured
form. For instance, if your data is already in the form of an array of arrays or a
Vector
of
Vector
objects, you can create a
JTable
without creating your own
TableModel
. A two-row-by-three-
column table could be created from the array of
{ { "Row1-Column1", "Row1-Column2",
"Row1-Column3"}, { "Row2-Column1", "Row2-Column2", "Row2-Column3"} }
, with another array
holding the column header names. Similar data structures would be necessary for the vector-
based constructor.
The remaining three constructors use
JTable
-specific data structures. If any one of the
three arguments is missing, default settings will be used. For example, if you don't specify a
TableColumnModel
, the default implementation
DefaultTableColumnModel
is used and is auto-filled
with a display order using the column order of the
TableModel
. When the selection model
is missing, the
ListSelectionModel
will use multiple-selection mode, which means that
noncontiguous rows, but not columns, can be selected.
Scrolling JTable Components
Like other components that may require more space than what is available, the
JTable
component
implements the
Scrollable
interface and should be placed within a
JScrollPane
. Scrollbars
will appear in a
JScrollPane
when a
JTable
is too big for the available screen real estate, and
column header names will appear above each column. Figure 18-3 shows how the table in
Figure 18-1 would appear if it weren't within a
JScrollPane
. Notice that neither column headers
nor scrollbars appear. This means you can't determine the meaning of the data, nor can you
scroll to the undisplayed rows.