Cell renderer class for a JComboBox in a JTable without parameters in the constructor

550 Views Asked by At

I am creating a cell renderer for a JComboBox in a JTable. The constructor of this class should take no parameter. I have the following basic code for the getTableCellRendererComponent method:

 public Component getTableCellRendererComponent(JTable table, Object value,  
              boolean isSelected, boolean hasFocus,int row, int column)  
 {  
     if (value != null) {  

    removeAllItems();  

         value = value_to_string;
         addItem(value); 


         if (isSelected) {
             this.setForeground(table.getSelectionForeground());
             super.setBackground(table.getSelectionBackground());
         } else {
             this.setForeground(table.getForeground());
             this.setBackground(table.getBackground());
         }

        // Select the current value
         this.setSelectedItem(value);  

     }  
     return this;  
 } 

The problem is that I would have as a value, instead of an Object, an array of String objects (String[]).I tried to use String[] value_to_string = (String[]) value; but this results in exceptions error being thrown. As I said, there shouldn't be any parameter in the constructor. Can someone find a way to solve this issue? Thanks in advance!

2

There are 2 best solutions below

0
On

The problem is that I would have as a value, instead of an Object, an array of String objects (String[]).

Then the data in your model is wrong. The TableModel should only contain a single value. It is the value that was selected from the combo box. The String[] is only used by the combo box editor, not the renderer.

0
On

You should adjust your TableModel.

@Override
public Class<?> getColumnClass(final int col) {
  return String[].class;
}

@Override
public Object getValueAt(final int row, final int col) {
  String[] yourStringArray = // some code
  return yourStringArray;
}

If you do it this way, you can cast the Object to String[] as you mentioned above in the renderer. String[] value_to_string = (String[]) value;