-1

注意:这段代码不是我的,我是从另一个站点获取的,我只是想修改它。

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

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

2 回答 2

1

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

if (row==theRowNumberToHighlight && column=0) {
  cell.setForeground(Color.red);
}
于 2013-03-26T12:59:19.810 回答
1

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

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

每次表中的数据更改时,都会调用此代码。

于 2013-03-26T13:22:05.900 回答