0

我正在为 JTable 中的 JComboBox 创建一个单元格渲染器。此类的构造函数不应带参数。对于 getTableCellRendererComponent 方法,我有以下基本代码:

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

问题是我将有一个字符串对象数组(String [])作为一个值,而不是一个对象。我尝试使用String[] value_to_string = (String[]) value;但这会导致抛出异常错误。正如我所说,构造函数中不应该有任何参数。有人能找到解决这个问题的方法吗?提前致谢!

4

2 回答 2

1

问题是我将有一个字符串对象数组(String [])作为一个值,而不是一个对象。

那么你模型中的数据是错误的。TableModel 应该只包含一个值。它是从组合框中选择的值。String[] 仅由组合框编辑器使用,而不是渲染器。

于 2011-10-15T14:40:21.187 回答
1

您应该调整您的 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;
}

如果你这样做,你可以像上面在渲染器中提到的那样将 Object 转换为 String[]。 String[] value_to_string = (String[]) value;

于 2011-10-16T07:55:56.793 回答