Reputation: 208
I want to create a JTable with JCombobox. In that JTable 3 columns having JComboBox with different data. I tried through DefaultCellEditor, but all the JCombobox having the same data.
Can anyone Help me to achieve the same.
Thanks in Advance.
public class CustomComboEditor extends DefaultCellEditor {
private DefaultComboBoxModel model;
private DefaultComboBoxModel model1;
private DefaultComboBoxModel model2;
public CustomComboEditor() {
super(new JComboBox());
this.model = (DefaultComboBoxModel) ((JComboBox) getComponent()).getModel();
this.model1 = (DefaultComboBoxModel) ((JComboBox) getComponent()).getModel();
this.model2 = (DefaultComboBoxModel) ((JComboBox) getComponent()).getModel();
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int col) {
try {
model.removeAllElements();
model.addElement("");
String sql = "select query 1";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
while (rs.next()) {
model.addElement(rs.getString(1));
}
model1.removeAllElements();
model1.addElement("");
String sql1 = "select query 2";
pst = conn.prepareStatement(sql1);
rs = pst.executeQuery();
while (rs.next()) {
model1.addElement(rs.getString(1));
}
/*model2.removeAllElements();
model2.addElement("");
model2.addElement("Male");
model2.addElement("Female");*/
} catch (SQLException ex) {
Logger.getLogger(Order_Enquiry.class.getName()).log(Level.SEVERE, null, ex);
}
return super.getTableCellEditorComponent(table, value, isSelected, row, col);
}
}
Upvotes: 1
Views: 226
Reputation: 4277
this.model = (DefaultComboBoxModel) ((JComboBox) getComponent()).getModel();
this.model1 = (DefaultComboBoxModel) ((JComboBox) getComponent()).getModel();
this.model2 = (DefaultComboBoxModel) ((JComboBox) getComponent()).getModel();
model
, model1
and model2
are 3 references pointing to the same object. So when you run model1.removeAllElements();
you are removing all the elements you just stored previously.
But one single model is probably fine. The problem is currently you are running the exact same queries, regardless of where you are in the table, so you can't hope to have different combobox entries in different cells. Instead you should have something more or less like:
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int col) {
model.removeAllElements();
model.addElement("");
if(col==0){
// Prepare query 1
sql = ...
}else if(col==1){
// Prepare query 2
sql = ...
}else
...
// run query
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
// Fill the model
while (rs.next()) {
model.addElement(rs.getString(1));
}
return super.getTableCellEditorComponent(table, value, isSelected, row, col);
}
Upvotes: 2