【问题标题】:Cell renderer class for a JComboBox in a JTable without parameters in the constructor构造函数中没有参数的 JTable 中的 JComboBox 的单元格渲染器类
【发布时间】:2011-12-08 06:57:45
【问题描述】:

我正在为 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;但这会导致抛出异常错误。正如我所说,构造函数中不应该有任何参数。有人能找到解决这个问题的方法吗?提前致谢!

【问题讨论】:

  • 1) 为了尽快获得更好的帮助,请发帖 SSCCE。 2) 将 String[] 条目放入组合中的用例是什么? 3) ListCellRenderergetListCellRendererComponent 方法,但没有 getTableCellRendererComponent 方法。
  • JCombobox在JTable中,感谢支持

标签: java swing jcombobox cellrenderer


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-16
      • 2011-10-02
      • 2013-02-24
      • 2013-02-10
      • 2012-03-05
      • 2015-03-07
      • 1970-01-01
      相关资源
      最近更新 更多