且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为jtable中列的每一行添加不同的组合框

更新时间:2021-10-11 07:06:12

Render这两列.

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);
 }
}