Update a combo box to display a specific Index within a JTable

405 views Asked by At

I have an existing content of values within a JComboBox located within a JTable column. What I am trying to do is read a value in from an exisiting object and update the ComboBox to show this value immediately.

My first attempt was to:

 // Sets up properties ComboBox
    propColumn = table.getColumnModel().getColumn(ENV_PROPERTIES_COLUMN);
    propComboBox = new JComboBox();
    propComboBox.addItem(""); // For initial empty string
    constructEnvProperties();

/**
 * Construct Environment Properties comboBox options
 */

     public void constructEnvProperties(){

           Vector<IWM781EnvProfileProperties> recordSet = dataMapperDatabase.getEnvironmentalProperties();

          // Iterate through vector and update combo box
                    for(int i = 0; i < recordSet.size(); i++){

                       logger.debug("Property: " + recordSet.get(i).getProp781Property());
                       propComboBox.addItem(recordSet.get(i).getProp781Property()); 
    }
}

Now when I want to update the ComboBox to a selected index I use the code:

if(record.getProp785MapProperty().compareTo("") != 0){

    ComboBoxModel model = propComboBox.getModel(); 
    int size1 = model.getSize();

       for (int i1 = 0; i1 < size1; i1++){

            String comparision = record.getRegv785MapRegister();

              if(comparision.equals(propComboBox.getItemAt(i1)))
                 propComboBox.setSelectedIndex(i1);
       }
 }

propColumn.setCellRenderer(new ComboBoxCellRenderer());
propColumn.setCellEditor(new DefaultCellEditor(propComboBox));  

When I debug through this it performs exactly as I would expect it to, but the table does not update.

I have tinkered with creating my own DefaultCellEditor to modify some of the functions. This allowed me to have flexibility with selecting specific cells to contain combo boxes and I am currently trying to modify this as a solution.

1

There are 1 answers

0
Nathan On BEST ANSWER

Figured out a solution to the problem just in case anybody else was looking at this and thinks, hmmm, I'm having similar issues. When I set up my TableModel I used the method:

   /**
   * Insert row into JTable
   * @param rowData
   */
public void insertRow (Object rowData){
    rows.add((Object[]) rowData);   
}

To add rows into the JTable.

When I was inserting rows into the JTable from my main, I was using:

 // Data to be inserted into the JTable     
        String[] data = new String[] {seqID, fieldName, type, size, "", value, "", "",""};
        tableModel.insertRow(data);

Because of the hard coded "" values, the combo boxes were automatically being assigned to the empty string that existed within the combo box. The quick fix was to create a String variable for each combo box value, perform specific checks on them to ensure there is data to be populated with and voila.

The solution looks simple and I feel quite stupid now .....