我制作了一个显示 JPanel 的自定义 TableCellRenderer。当 JPanel 包含交互元素时,我希望它们也能正常工作,所以我制作了一个自定义 TableCellEditor。它可以工作,但是单击 JPanel 时会出现一些奇怪的行为。有时,单击时 JPanel 会消失。当我只设置自定义渲染器时,根本没有问题,除了 JPanel 不是交互式的。所以问题一定出在TableCellEditor上。
编辑:
public class PanelTableCellEditor
extends AbstractCellEditor
implements TableCellEditor
{
private Object _component;
@Override
public Object getCellEditorValue()
{
return _component;
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int row,
int column)
{
_component = value;
if (value instanceof JPanel)
{
((Component) value).setForeground(UIManager.getColor("List.selectionForeground"));
((Component) value).setBackground(UIManager.getColor("List.selectionBackground"));
return ((Component) value);
}
else
{
return null;
}
}
}
渲染器:
public class PanelTableCellRenderer
extends Component
implements TableCellRenderer
{
@Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected,
boolean hasFocus, int row,
int column)
{
if (value instanceof JPanel)
{
if (isSelected || hasFocus)
{
((Component) value).setForeground(UIManager.getColor("List.selectionForeground"));
((Component) value).setBackground(UIManager.getColor("List.selectionBackground"));
}
else
{
((Component) value).setForeground(UIManager.getColor("Panel.foreground"));
((Component) value).setBackground(UIManager.getColor("Panel.background"));
}
return ((Component) value);
}
else
{
return new DefaultTableCellRenderer().getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
}
}
}
在主窗体中,我有下一个代码:
DefaultTableModel model = new DefaultTableModel();
model.addColumn(null, new Object[]
{
jPanel1, jPanel2, jPanel1, jPanel2, jPanel1, jPanel2, jPanel1, jPanel2, jPanel1, jPanel2, jPanel1
});
jTable1.setModel(model);
TableColumn column = jTable1.getColumnModel().getColumn(0);
column.setCellRenderer(new PanelTableCellRenderer());
column.setCellEditor(new PanelTableCellEditor());
jTable1.setRowHeight(50);
jTable1.setTableHeader(null);
jScrollPane2.setColumnHeaderView(null);