【发布时间】:2023-03-22 15:03:01
【问题描述】:
我为JTable 单元格设置了jCombobox 为DefaultCellEditor。
当我在单元格 (jCombobox) 中键入一个值时出现问题,并且每当我单击其他位置时,该值都会丢失。有人知道为什么以及如何解决这个问题?
table.getColumnModel().getColumn(1).setCellEditor(new SpringJobTablePopupCellEditor());
public class SpringJobTablePopupCellEditor extends AbstractCellEditor implements TableCellEditor {
JTextField jtf;
DefaultCellEditor other;
DefaultCellEditor checkbox;
private DefaultCellEditor lastSelected;
JComboBox cbox = null;
public SpringJobTablePopupCellEditor() {
jtf = new JTextField();
jtf.setDocument(new JTextFieldLimit(1000));
other = new DefaultCellEditor(jtf);
checkbox = new DefaultCellEditor(generateBox("10"));
}
@Override
public Object getCellEditorValue() {
return lastSelected.getCellEditorValue();
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
final JTable t = table;
cbox.getEditor().getEditorComponent().addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void focusLost(FocusEvent e) {
if(t.isEditing()){
t.getCellEditor().stopCellEditing();
}
}
});
String val = table.getModel().getValueAt(row, column - 1).toString();
if("ak".equals(val)){
lastSelected = checkbox;
return checkbox.getTableCellEditorComponent(table, value, isSelected, row, column);
}
lastSelected = other;
return other.getTableCellEditorComponent(table, value, isSelected, row, column);
}
private JComboBox generateBox(String type) {
cbox = new JComboBox();
cbox.setEditable(true);
for (Map.Entry<String, String> entry : SpringJob.akMap.entrySet()) {
cbox.addItem(entry.getValue());
}
return cbox;
}
}
【问题讨论】:
-
如果我没记错的话,表格编辑器失去焦点的默认行为是取消编辑
-
同时验证你对
setValueAt()的实现。
标签: java swing jtable jcombobox