我有一个JTable
它的一列单元格是JComboBox
。但是当点击表格单元格时尝试获取行数时JComboBox
,我发现行索引总是返回错误值(总是最后一次点击的行索引)。
public class TableComboBoxTest extends JFrame {
private JTable table;
private DefaultTableModel tableModel;
private Object[][] tableCells;
private final String[] TABLE_COLUMNS = {"No.1"};
private final String[] YES_NO_SELECTION = {"Yes", "No"};
public TableComboBoxTest() {
Container pane = getContentPane();
pane.setLayout(new BorderLayout());
tableModel = new DefaultTableModel(tableCells, TABLE_COLUMNS);
table = new JTable(tableModel);
DefaultCellEditor cellEditor = null;
JComboBox selA = new JComboBox(YES_NO_SELECTION);
cellEditor = new DefaultCellEditor(selA);
cellEditor.setClickCountToStart(1);
table.getColumn(TABLE_COLUMNS[0]).setCellEditor(cellEditor);
JScrollPane jsp = new JScrollPane();
jsp.getViewport().add(table, null);
pane.add(jsp, BorderLayout.CENTER);
TableCellEditor tce = null;
addRow("Yes");
outputDefaultSelection(0, 0);
addRow("No");
outputDefaultSelection(1, 0);
System.out.println("");
selA.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
JComboBox cb = (JComboBox) e.getSource();
String sel = (String) cb.getSelectedItem();
int rowIndex = table.getSelectedRow();
rowIndex = table.convertRowIndexToModel(rowIndex);
if (rowIndex == -1) {
return;
}
outputDefaultSelection(rowIndex, 0);
System.out.println("Select: " + sel + " at " + rowIndex);
}
}
});
}
private void addRow(String v1) {
Vector<String> vec = new Vector<String>();
vec.add(v1);
tableModel.addRow(vec);
tableModel.fireTableDataChanged();
}
private void outputDefaultSelection(int row, int col) {
TableCellEditor tce = table.getCellEditor(row, col);
System.out.println("Default " + row + "-" + col + " Selection: " + tce.getCellEditorValue());
System.out.println("Default " + row + "-" + col + " Value: " + table.getModel().getValueAt(row, col));
}
public static void main(String[] args) {
TableComboBoxTest stt = new TableComboBoxTest();
stt.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
stt.setSize(200, 100);
stt.setVisible(true);
}
}
默认 0-0 选择:是 默认 0-0 值:是 默认 1-0 选择:是 默认 1-0 值:否*
单击第一行并选择“是”时,不会触发更改事件。单击第二行时,更改事件触发器!行号错误:0
默认 0-0 选择:否 默认 0-0 值:是 选择:否在 0*
当继续点击第一行时,改变事件触发器!行号错误:1
默认 1-0 选择:是 默认 1-0 值:否 选择:是 1
如何获得正确的点击单元格编号?
而对于 itemStateChanged 过程,我还发现如果单元格设置值与默认列值相同(“是”),单击它时不会触发事件。但如果单元格设置值为“否”,单击它会导致更改事件。这意味着模型数据与默认选择的数据不同。如何使它们保持一致?
谢谢~