Java Reference
In-Depth Information
Editing Table Cells
Editing
JTable
cells is nearly identical to editing
JTree
cells. In fact, the default table cell editor,
DefaultCellEditor
, implements both the
TableCellEditor
and
TreeCellEditor
interfaces,
allowing you to use the same editor for both tables and trees.
Clicking an editable cell will place the cell in edit mode. (The number of clicks required
depends on the type of editor.) The default editor for all cells is a
JTextField
. Although this
works great for many data types, it's not always appropriate for many others. So, you should
either not support editing of nontextual information or set up specialized editors for your
JTable
. With a
JTable
, you register an editor for a particular class type or column. Then, when
the table runs across a cell of the appropriate type, the necessary editor is used.
■
Caution
When no specialized editor is installed, the
JTextField
is used, even when it's inappropriate
for the content.
TableCellEditor Interface and DefaultCellEditor Class
The
TableCellEditor
interface defines the single method necessary to get an editor cell for a
JTable
. The argument list for
TableCellEditor
is identical to the
TableCellRenderer
, with the
exception of the
hasFocused
argument. Because the cell is being edited, it's already known to
have the input focus.
public interface TableCellEditor extends CellEditor {
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int row, int column);
}
As described in Chapter 17, the
DefaultCellEditor
provides an implementation of the
interface. It offers a
JTextField
as one editor, a
JCheckBox
for another, and a
JComboBox
for a third.
As Table 18-13 shows, in most cases the default editor is the
JTextField
. If the cell data can
be converted to and from a string, and the class provides a constructor with a
String
argument,
the editor offers the text representation of the data value for the initial editing value. You can
then edit the contents.
Table 18-13.
Default JTable Editors
Class
Editor
Information
Boolean
JCheckBox
Centered
Object
JTextField
Left-aligned
Creating a Simple Cell Editor
As a simple example of changing a non-
String
cell in a
JTable
, you can provide a fixed set of
color choices to the user. Then when the user picks a color, you have the appropriate
Color
value to