我有一个使用JComboBox作为单元格编辑器的自定义TableModel的自定义JTable。 ComboBox也有一个自定义ComboBoxModel ComboBox模型包含多个字段,这些字段将用于更新JTable后面的数据并随后更新数据库。JComboBox作为带有Overriden的Jtable CellEditor stopCellEditing修改错误的表格单元格
以下是显示我遇到的问题的简单示例。重现步骤:
- 单击一个细胞
- 从ComboBox中选择下拉列表
- 点击不同的细胞
- 点击后面的第一个选择的小区上
第二个单元格将获得第一个单元格的值。
这是怎么发生的?为什么ComboBox模型在stopCellEditing存在之前更改?
import javax.swing.DefaultCellEditor;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class TestComboCellEditor {
public static void main(String[] args) {
TestComboCellEditor test = new TestComboCellEditor();
test.go();
}
public void go() {
//create the frame
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// create and add a tabbed pane to the frame
JTabbedPane tabbedPane = new JTabbedPane();
frame.getContentPane().add(tabbedPane);
//create a table and add it to a scroll pane in a new tab
final JTable table = new JTable(new DefaultTableModel(new Object[]{"A", "B"}, 5));
JScrollPane scrollPane = new JScrollPane(table);
tabbedPane.addTab("test", scrollPane);
// create a simple JComboBox and set is as table cell editor on column A
Object[] comboElements = {"aaaaa1", "aaaaaa2", "b"};
final JComboBox comboBox = new JComboBox(comboElements);
comboBox.setEditable(true);
table.getColumn("A").setCellEditor(new DefaultCellEditor(comboBox) {
@Override
public boolean stopCellEditing() {
if (comboBox.isEditable()) {
DefaultComboBoxModel comboModel = (DefaultComboBoxModel) comboBox.getModel();
String selectedItem = (String) comboModel.getSelectedItem();
int selectedIndex = comboModel.getIndexOf(selectedItem);
if (!(selectedIndex == -1)) {
// the selected item exists as an Option inside the ComboBox
DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
int selectedRow = table.getSelectedRow();
int selectedColumn = table.getSelectedColumn();
tableModel.setValueAt(selectedItem, selectedRow, selectedColumn);
} else if (selectedItem != null) {
// missing code - adding new info to a custom JComboBox model and to alter info inside a custom table model
}
}
return super.stopCellEditing();
}
});
// pack and show frame
frame.pack();
frame.setVisible(true);
}
}
执行无效:编辑**不能**更改视图/模型调用它 - 它的唯一责任是通知编辑完成并保持编辑值(为其客户端访问) – kleopatra
我的第一次尝试是这样的:http://stackoverflow.com/questions/19938204/return-the-focus-to-jcombobox- jtable-after-showoptiondialog/19938451#19938451但遇到其他问题,所以我被推荐去这种方式。我一直在寻找最佳实践来实现我想要的东西,但找不到要使用的东西。如果你可以用一个例子来指向一个链接,它会很棒。 –