我有一个应该是2列的JTable(String,JComboBox)。当我初始化表时,一切看起来都很好。只要我在表中选择一个值,JComboBox单元就会获取所选项的数据类型。
我想保留JCOmboBox并让它触发数据更改事件,Table忽略该列中的数据更改并保持ComboBox的填充。
我的表格将此作为覆盖
@Override
public TableCellEditor getCellEditor(int row, int column) {
Object value = super.getValueAt(row, column);
if (value != null) {
if (value instanceof JComboBox) {
return new DefaultCellEditor((JComboBox) value);
}
return getDefaultEditor(value.getClass());
}
return super.getCellEditor(row, column);
}
实施
JComboBox uploadBox = new JComboBox();
uploadBox.addItem(MyPanel.UPLOAD_OPTIONS.PROMPT);
uploadBox.addItem(MyPanel.UPLOAD_OPTIONS.UPLOAD);
uploadBox.addItem(MyPanel.UPLOAD_OPTIONS.DONT_UPLOAD);
Object[][] tableData = new Object[][]{
{"Upload data on save", uploadBox}
};
table.setModel(
new DefaultTableModel(tableData, new String[]{"Description", "Options"}) {
Class[] types = new Class[]{String.class, JComboBox.class};
boolean[] canEdit = new boolean[]{false, true};
@Override
public Class getColumnClass(int columnIndex) {
return types[columnIndex];
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit[columnIndex];
}
});
table.getColumnModel().getColumn(1).setCellRenderer(new TableCellRenderer() {
@Override
public Component getTableCellRendererComponent(JTable jtable, Object o, boolean bln, boolean bln1, int i, int i1) {
return (Component)o;
}
});
答案 0 :(得分:3)
回答非常简单,不要将JComboBox
添加到XxxTableModel
或为getColumClass
设置JComboBox.class
,这是错误的(确定可行,但是一堆副作用),XxxTableModel
(指定用于)只能直接保存标准Java数据类型(String
,Date
,Icon
/ ImageIcon
,{ {1}},Integer
等......)
Double
应该存储(如果你不想在Java数据类型之间解析)相同的数据类型,如XxxTableModel
中存储的那样(注意清楚是什么constans {{ 1}}),例如,当DefaultComboBoxModel
具有相同的数据类型时MyPanel.XXX
存储XxxTableModel
值,String
,DefaultComboBoxModel
/ {{1}的类似逻辑}},Date
或Icon
有关阅读Oracle教程How to use Tables - Using a Combo Box as an Editor