自定义我的细胞渲染器以更改一个细胞颜色?

时间:2013-03-26 12:41:17

标签: java swing colors jtable tablecellrenderer

注意:此代码不是我的,我从其他网站上获取它,我只是想修改它。

我有一个带有大量细节的JTable,但我想要它,以便当我更改第一个单元格的特定单元格来改变颜色时。目前这个代码只是在我点击它时突出显示该行,但我想要它,以便如果我将其中一个值更改为另一个数字,则名称单元格例如更改为红色。我尝试了一些事情(如果声明),但似乎无法正常工作。任何帮助都会很棒。

import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;

public class CustomCellRenderer{
   JTable table;
   TableColumn tcol;
   public static void main(String[] args) {
   new CustomCellRenderer();
   }

  public CustomCellRenderer(){
   JFrame frame = new JFrame("Creating a Custom Cell Reanderer!");
   JPanel panel = new JPanel();
   String data[][] = {{"Vinod","Computer","3"},
    {"Rahul","History","2"},
    {"Manoj","Biology","4"},
    {"Sanjay","PSD","5"}};
   String col [] = {"Name","Course","Year"};
   DefaultTableModel model = new DefaultTableModel(data,col);
   table = new JTable(model);
   tcol = table.getColumnModel().getColumn(0);
   tcol.setCellRenderer(new CustomTableCellRenderer());
   tcol = table.getColumnModel().getColumn(1);
   tcol.setCellRenderer(new CustomTableCellRenderer());
   tcol = table.getColumnModel().getColumn(2);
   tcol.setCellRenderer(new CustomTableCellRenderer());
   JTableHeader header = table.getTableHeader();
   header.setBackground(Color.yellow);
   JScrollPane pane = new JScrollPane(table);
   panel.add(pane);
   frame.add(panel);
   frame.setSize(500,150);
   frame.setUndecorated(true);
   frame.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.setVisible(true);
   }

  public class CustomTableCellRenderer extends DefaultTableCellRenderer{
   public Component getTableCellRendererComponent (JTable table, 
 Object obj, boolean isSelected, boolean hasFocus, int row, int column) {
   Component cell = super.getTableCellRendererComponent(
    table, obj, isSelected, hasFocus, row, column);
   if (isSelected) {
   cell.setBackground(Color.green);
   } 
   else {
   if (row % 2 == 0) {
   cell.setBackground(Color.lightGray);
   }
   else {
   cell.setBackground(Color.lightGray);
   }
   }
   return cell;
   }
   }
 } 

2 个答案:

答案 0 :(得分:1)

如果您知道要突出显示的行号,只需在getTableCellRendererComponent方法的末尾添加

if (row==theRowNumberToHighlight && column=0) {
  cell.setForeground(Color.red);
}

答案 1 :(得分:1)

假设您的表模型扩展了AbstractTableModel,请扩展TableModelListener。使用下面的tableChanged方法来确定何时调用渲染器:

public void tableChanged(TableModelEvent e)  
{  
    if (e.getColumn() == columnYouAreChecking && e.getFirstRow() == rowYouAreChecking && e.getLastRow() == rowYouAreChecking)
    {
        // Change cell color here.
    }  
}

每次表格中的数据发生变化时,都会调用此代码。