我有一個使用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但遇到其他問題,所以我被推薦去這種方式。我一直在尋找最佳實踐來實現我想要的東西,但找不到要使用的東西。如果你可以用一個例子來指向一個鏈接,它會很棒。 –