Render
both the columns.
TableColumn comboCol1 = table.getColumnModel().getColumn(0);
TableColumn comboCol2 = table.getColumnModel().getColumn(1);
comboCol1.setCellEditor(new CustomComboBoxEditor());
comboCol2.setCellEditor(new CustomComboBoxEditor());
// This is for 2nd Column which depends on the first column selection.
public class CustomComboBoxEditor extends DefaultCellEditor {
// Declare a model that is used for adding the elements to the `ComboBox`
private DefaultComboBoxModel model;
public CustomComboBoxEditor() {
super(new JComboBox());
this.model = (DefaultComboBoxModel)((JComboBox)getComponent()).getModel();
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
if(column == 0) {
// Just show the elements in the JComboBox.
} else {
// Remove previous elements every time.
// So that we can populate the elements based on the selection.
model.removeAllElements();
// getValueAt(..) method will give you the selection that is set for column one.
String selectedItem = table.getValueAt(row, 0);
// Using the obtained selected item from the first column JComboBox
// selection make a call ans get the list of elements.
// Say we have list of data from the call we made.
// So loop through the list and add them to the model like the following.
for(int i = 0; i < obtainedList.size(); i++) {
model.addElement(obtainedList.get(i));
}
} // Close else
// finally return the component.
return super.getTableCellEditorComponent(table, value, isSelected, row, column);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…