0

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!

Anto
  • 4,265
  • 14
  • 63
  • 113
  • 2
    1) For better help sooner, post an [SSCCE](http://pscode.org/sscce.html). 2) What is the use-case for putting String[] entries in the combo? 3) A `ListCellRenderer` has a `getListCellRendererComponent` method, but no `getTableCellRendererComponent` method. – Andrew Thompson Oct 15 '11 at 10:04
  • the JCombobox is in a JTable, thanks for the support – Anto Oct 15 '11 at 10:09

2 Answers2

1

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.

camickr
  • 321,443
  • 19
  • 166
  • 288
1

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;

Stephan
  • 4,395
  • 3
  • 26
  • 49