java - 在运行时为 JTable 的特定行设置背景颜色

标签 java swing colors jtable

我正在使用 netbeans IDE7.4,我在运行时向 JTable 添加行,现在我想为特定行设置背景颜色。

现在的问题是,当该行的值更改时,该特定行的颜色没有更改,而当我向上或向下滚动表格时,应用更改。

如何在运行时刷新表?如何在运行时设置特定行的背景颜色?

这是用于为特定行着色的渲染器类:

public class MyCellRenderer extends javax.swing.table.DefaultTableCellRenderer
    {         
public java.awt.Component getTableCellRendererComponent(javax.swing.JTable table, java.lang.Object value, boolean isSelected,     boolean hasFocus, int row, int column)
   {
   final java.awt.Component cellComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row,        column);

     Object val=table.getValueAt(row, 2);
     String sval=val.toString();
     sval=sval.replaceAll(":","");
     int ival=Integer.parseInt(sval);
  if(ival==0) 
    {  
        cellComponent.setForeground(Color.black);          
        cellComponent.setBackground(Color.red);              

    }      
    else  
    {      
        cellComponent.setBackground(Color.white);      
        cellComponent.setForeground(Color.black);      
    }    
    if (isSelected)
   {
    cellComponent.setForeground(table.getSelectionForeground());                             cellComponent.setBackground(table.getSelectionBackground());
   }


      return cellComponent;

 }


 }

并像这样分配给 jtable :

    newViewTable.setDefaultRenderer(Object.class,new MyCellRenderer());

newViewTable 是 JTable 的名称。

最佳答案

how to set background color of particular row at runtime?

使用表格单元格渲染器。参见 How to Use Tables: Using Custom Renderers了解详情。

关于java - 在运行时为 JTable 的特定行设置背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22524879/

相关文章:

c# - 读取同风格的dox,docx文件

Java颜色检测

java - 聚合根类是否仅包含公开暴露的方法

java - 来自证书颁发机构的 java 代码签名需要多少钱?

java - Apache Kafka Java 生产者 Scala 消费者缺少流

java - 如何在Java中实现一个组合框,为所选项目输出一定的数字?

java - 创建 ImageIcon 时 getClass().getResource(...) 做了什么?

objective-c - 如何计算RGB颜色中颜色分量的 "amount"

java - 为什么这段代码特别出现 3 个错误?

java - 从 spring 创建 EhCache 缓存时出现问题