如何使JTable列根据数据库中的特定值更改颜色

时间:2011-09-29 20:40:04

标签: swing jdbc jtable client-server

我正在构建客户端/服务器桌面应用程序。

我想知道是否可以根据数据库(oracle)中的特定值创建 JTable Column 更改其颜色

  • 红色 =“拒绝”。
  • 绿色 = “接受”。
  • 黄色 = “隔离区”。

2 个答案:

答案 0 :(得分:2)

使用适当的renderer

答案 1 :(得分:1)

为此使用自定义列渲染器:

public class ColorColumnRenderer extends DefaultTableCellRenderer 
{
   Color bkgndColor, fgndColor;

   public ColorColumnRenderer(Color bkgnd, Color foregnd) {
      super(); 
      bkgndColor = bkgnd;
      fgndColor = foregnd;
   }

   public Component getTableCellRendererComponent
        (JTable table, Object value, boolean isSelected,
         boolean hasFocus, int row, int column) 
   {
      Component cell = super.getTableCellRendererComponent
         (table, value, isSelected, hasFocus, row, column);

      cell.setBackground( bkgndColor );
      cell.setForeground( fgndColor );

      return cell;
   }
}

您可以像这样使用该渲染器(单个列的示例):

TableColumn tm = table.getColumnModel().getColumn(0);
tm.setCellRenderer(new ColorColumnRenderer(Color.lightGray, Color.blue));

获得换色代码后,您可以创建一个listener来监听表模型的值更改,并通过检查更改,您可以将所需的颜色应用于特定列。