1

好的,在过去的露水时间里,我一直在尝试这样做,但它变得无望了。

所以我想将单元格渲染应用于第二列。

stockTable.setCellRender(jtSpread.getColumnModel().getColumn(1));

调用的方法是 setCellRender,其代码如下:

public void setCellRender(TableColumn column)
{
    column.setCellRenderer(new cellRenderer(data, rows));
}

我的 CellRenderer 类具有以下代码:

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

  for(int i = 0; i < rows; i++) {
      if(row == i && column == 2) {

      }
  }
  return this;
}

以上是不完整的,一团糟。我的目标是检查每个单元格的条件,如果为真,那么我将返回带有绿色前景的标签。如果为 false,则返回具有红色前景的标签。我想逐个检查列中的每个单元格,并且每个条件都特定于每个单元格。

编辑:关于每个单元格都有自己的条件,例如。

第一个单元格的值为 600,我想检查数组 [0],如果数组 [0] 的内容更高,我希望单元格为绿色,否则为红色。

第二个单元格的值为 626,我想检查数组 [1],如果数组 [1] 的内容更高,我希望单元格为绿色,否则为红色。

我想针对数组中的所有值继续列中的所有单元格

4

2 回答 2

5

确保您的渲染器扩展 DefaultTableCellRenderer:

CellRenderer extends DefaultTableCellRenderer {
   ...  

然后,getTableCellRendererComponent()可能看起来像这样(每次呈现单元格时都会调用此方法):

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

    Component cellComponent = super.getTableCellRendererComponent(
          table, value, isSelected, hasFocus, row, column);
     cellComponent.setForeground(isMyConditionFullfilled(value) ? Color.GREEN : Color.RED);
     return cellComponent;    
}
于 2012-03-10T21:37:36.500 回答
1

您的渲染类必须实现 TableCellRender 在您的渲染类中试试这个:

public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        JLabel label = new JLabel();
        label.setOpaque(true);
        if (value != null && value.equals("text")) { //Checking if  cell´s values isnt null and the condition is true
            label.setBackground(Color.GREEN);
        }else{
            label.setBackground(Color.RED);
        }
        return label;
    }

渲染器将​​自己检查每个单元格,只需告诉它如何渲染每个单元格。变量“value”包含每一行的值,因此您可以使用它来检查条件。如果您的列定义了类型,请转换变量“值”。例如,如果您的单元格定义了 Double 类型:

double valDouble = (Double) value;
if (value != null && value == 5.00) { //Checking if  cell´s values isnt null and the condition is true
        label.setBackground(Color.GREEN);
 }else{
        label.setBackground(Color.RED);
  }
于 2012-03-10T21:42:36.963 回答