如果写Editor的话, 实现理念是一样的. 不过应该写在Editor中isCellEditable方法, 例如
public class ColorEditor extends AbstractCellEditor implements TableCellEditor {
private JLabel label = new JLabel();
private Color color = null;
public ColorEditor() {
}
public Object getCellEditorValue() {
return color;
}
public boolean isCellEditable(EventObject e) {
if (e instanceof MouseEvent) {
MouseEvent me = (MouseEvent) e;
JTable table = (JTable) e.getSource();
int row = table.rowAtPoint(me.getPoint());
int col = table.columnAtPoint(me.getPoint());
Color color = (Color) table.getValueAt(row, col);
You have a fundamental misunderstanding of rendering.
The component returned from a cell renderer is merely
"rubber stamped" or painted into the component using
the cell renderer. The renderer component is NOT
actually placed into the component using the cell
renderer.
In order to do what you want to do you need to implement
a cell editor.
Also, note that DefaultTableCellRenderer *extends* JLabel.
The getTableCellRendererComponent returns a JLabel, which
is actually *this*.
Your cell renderer (or editor) should NOT create a new
component each time getTableCellRenderer() is called. It
should re-use one instance of each type of component that
might be returned, modifying it as needed, before returning
it. I cannot say exactly why, but if you don't heed this
advice, your code will have a memory leak, and your JVM
could eventually run out of memory.