Before, I set combobox as editor in JTable like this code below. But it can't work like I want just like I posted the problem in my first post above.
DefaultTableModel model;
TableColumn comboboxColumn;
final JComboBox cboBarang = new JComboBox();
tabel.setModel(model);
comboboxColumn = tabel.getColumnModel().getColumn(0);
isiCboBarang(cboBarang);
comboboxColumn.setCellEditor(new DefaultCellEditor(cboBarang));
So, now I tried to use tableCellEditor, and this is my code:
tabel.setModel(model);
comboboxColumn = tabel.getColumnModel().getColumn(0);
comboboxColumn.setCellEditor(new MyComboBoxEditor());
public class MyComboBoxEditor extends JComboBox implements TableCellEditor, ItemListener {
Vector editorListeners;
public MyComboBoxEditor() {
super();
editorListeners = new Vector();
System.out.println(listItem);
for(int i =0; i < listItem.size(); i++){
addItem(listItem.get(i));
}
addItemListener(this);
}
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
// Select the current value
setSelectedItem(value);
return this;
}
public Object getCellEditorValue() {
return this.getSelectedItem();
}
public boolean isCellEditable(EventObject anEvent) {
return true;
}
public boolean shouldSelectCell(EventObject anEvent) {
return true;
}
public boolean stopCellEditing() {
return true;
}
public void cancelCellEditing() {
}
public void addCellEditorListener(CellEditorListener l) {
editorListeners.add(l);
}
public void removeCellEditorListener(CellEditorListener l) {
editorListeners.remove(l);
}
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange()==ItemEvent.DESELECTED)
{
Statement stmt;
ResultSet rs;
try {
//generate code
sql = "SELECT desc_bar FROM inv_item WHERE kode_bar = '" +
this.getSelectedItem() + "'";
stmt = Koneksi.getConnection().createStatement();
rs = stmt.executeQuery(sql);
if (rs.last()){
tabel.setValueAt(rs.getString(1), tabel.getSelectedRow(), 1);
} else {
tabel.setValueAt("", tabel.getSelectedRow(), 1);
}
rs.close();
stmt.close();
} catch (SQLException ex) {
Logger.getLogger(TrPOEntry.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
With this method, it's running but not properly. For example, combobox's data are: "A", "B", "C". When I choose "A" (col 1, row 1), the second column in the first row (col 2, row1) will display "1". After I choose combobox in first row, next I'm going to combobox in second row (col 1, row 2). But apparently, the second column in first row (col 2, row 1) change the content according to the value in combobox second row (col 1, row 2).
So, I guess when I move on to different row (but still in the jcombobox column), combobox still in editing state. Because it didn't happen when I first click column 1 (combobox column), then I click different column (besides combobox column). So, how can I fix this and it stop editing after I move on to the next row? Please help me.. :confused: