Add different combobox for each row of a column in a jtable

前端 未结 1 390
轻奢々
轻奢々 2020-12-12 01:12
public class TablePanel extends JPanel implements ActionListener,Serializable
{
    JTable m_table;
    JComboBox combo,combo1;
    DefaultTableModel model=new Defau         


        
相关标签:
1条回答
  • 2020-12-12 01:33

    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);
     }
    }
    
    0 讨论(0)
提交回复
热议问题