![]() |
The Java Developers Almanac 1.4 |
|
e927. Using Built-In Cell Renderers and Editors in a JTable ComponentThere are built-in cell renderers and editors available for seven types:Boolean, Date, Double, Float,
Icon, Number, and Object. By default every column
uses the Object cell renderer and editor, regardless of the
column data type. There are two typical ways to force a column to use
a particular cell renderer and editor.
The first way is to have the table model's
The second way is to find the DefaultTableModel model = new DefaultTableModel() {
// This method returns the Class object of the first
// cell in specified column in the table model.
// Unless this method is overridden, all values are
// assumed to be the type Object.
public Class getColumnClass(int columnIndex) {
Object o = getValueAt(0, columnIndex);
if (o == null) {
return Object.class;
} else {
return o.getClass();
}
}
};
JTable table = new JTable(model);
// Add a column for each of the available renderers
model.addColumn("Boolean", new Object[]{Boolean.TRUE});
model.addColumn("Date", new Object[]{new Date()});
model.addColumn("Double", new Object[]{new Double(Math.PI)});
model.addColumn("Float", new Object[]{new Float(1.2)});
model.addColumn("Icon", new Object[]{new ImageIcon("icon.gif")});
model.addColumn("Number", new Object[]{new Integer(1)});
model.addColumn("Object", new Object[]{"object"});
// Explicitly set the Boolean cell renderer and editor on the
// TableColumn showing the first column in the table model
int mColIndex = 0;
findTableColumn(table, mColIndex).setCellRenderer(table.getDefaultRenderer(Boolean.class));
findTableColumn(table, mColIndex).setCellEditor(table.getDefaultEditor(Boolean.class));
// Returns the TableColumn associated with the specified column
// index in the model
public TableColumn findTableColumn(JTable table, int columnModelIndex) {
Enumeration enum = table.getColumnModel().getColumns();
for (; enum.hasMoreElements(); ) {
TableColumn col = (TableColumn)enum.nextElement();
if (col.getModelIndex() == columnModelIndex) {
return col;
}
}
return null;
}
e928. Creating a Custom Cell Renderer in a JTable Component e929. Creating a Class-Based Custom Cell Renderer in a JTable Component e930. Copying Cell Values to the Clipboard from a JTable Component
© 2002 Addison-Wesley. |