JComboBox
中的{p> TableCellEditor
会记住不同行中的最后一个选定值,甚至不同TableModels
。例如,在一行中选择一个值,然后转到另一行,开始单元格编辑,JComboBox
将在previos行上将当前值作为最后一个选择值。
如何修复?
答案 0 :(得分:3)
在getTableCellEditorComponent(..)
方法中设置值。
示例:
public static void main(String... args) {
JFrame frame = new JFrame("Test");
JTable table = new JTable(10, 2);
JComboBox box = new JComboBox(new String[] {"A", "B", "C"});
table.setDefaultEditor(Object.class, new DefaultCellEditor(box) {
@Override
public Component getTableCellEditorComponent(JTable table,
Object value, boolean isSelected, int row, int column) {
return super.getTableCellEditorComponent(
table,
table.getValueAt(Math.max(row-1, 0), column),
isSelected,
row,
column);
}
});
frame.add(table);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.setVisible(true);
}