繁体   English   中英

为JTable内的列中的特定单元格着色

[英]Coloring a specific cell in a column inside a JTable

好吧,在过去的露水时间里,我一直在尝试这样做,现在已经变得毫无希望了。

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

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

以上内容不完整,一团糟。 我的目的是检查每个单元格的状况,如果为true,则返回带有绿色前景的标签。 如果为false,则返回带有红色前景的标签。 我想一栏中检查每个单元格,每个条件都特定于每个单元格。

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

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

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

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

确保您的渲染器扩展了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;    
}

您的渲染类必须实现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;
    }

渲染器将​​自己检查每个单元格,只告诉它如何渲染每个单元格。 变量“值”包含每一行的值,因此您可以使用它来检查条件。 如果您的列已定义类型,则将变量“值”强制转换。 例如,如果您的单元格定义了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);
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM