Switching values when editing a cell
I have a JTable which开发者_JAVA百科 uses a custom TableModel to display a series of object instances. There's a switch case inside getValueAt(int row, int column)
to return values according to given attributes (see below). One return statement involves returning a value of 1/0 as true/false.
Is there a way that I can modify this TableModel so that it displays a 1/0 when a cell is edited?
public Object getValueAt(int row, int column) {
User user = (User)dataVector.get(row);
switch (column) {
case ID_INDEX:
return user.getId();
case USERNAME_INDEX:
return user.getUserName();
case PASSWORD_INDEX:
return "****";
case ACTIVATED_INDEX:
return (user.getActivated())?"true":"false";
default:
return new Object();
}
}
The default renderer and editor for Boolean
is a JCheckBox
. Consider using
case ACTIVATED_INDEX:
return Boolean.valueOf(user.getActivated());
Alternatively,
case ACTIVATED_INDEX:
return (user.getActivated())?"1":"0";
Addendum: As an example, DefaultTableModel
does not override getColumnClass()
, and AbstractTableModel
simply returns Object.class
. Your TableModel
should override getColumnClass()
accordingly:
DefaultTableModel dtm = new DefaultTableModel() {
@Override
public Class<?> getColumnClass(int col) {
return getValueAt(0, col).getClass();
}
};
// add some data
JTable table = new JTable(dtm);
You need to have a look at TableCellRenderer
and TableCellEditor
:
A TableCellRenderer
is responsible for rendering cell data when it is not being edited, where as a TableCellEditor
is responsible for providing a component used to edit the value of a cell. You can therefore represent the data in two separate ways depending on whether it is being edited or just rendered as per normal.
You should however consider that if you return a Boolean type from the getValueAt() method, your JTable should automatically render a JCheckBox, when the cell is in edit mode, the JCheckBox value can be changed by clicking on it as usual. To do this just return:
case ACTIVATED_INDEX:
return Boolean.valueOf(user.getActivated());
精彩评论