java表CustomTableCellRenderer根据单元格内容值更改行颜色

时间:2013-11-30 18:12:13

标签: java swing colors jtable tablecellrenderer

我正在开发java应用程序。我想在一个包含3列名称课程和年份的表格中显示数据。我根据在互联网上找到的教程使用tablerenderer。这段代码实际上是用青色和灰色颜色着色行行号。但是我想将青色设置为行,只有当年份列(年份值)等于某个值时,让我们说3.这意味着如果第3行年份列值等于5则第3行颜色应该青色,否则应该是灰色的。这是我在互联网上找到的代码..所以我怎样才能为我的目标修改它?

import java.awt.Color;
import java.awt.Component;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;


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","5"},
   {"Sanjay","PSD","6"}};
  String col [] = {"Name","Course","Year"};
  DefaultTableModel model = new DefaultTableModel(data,col);
  table = new JTable(model);
  tcol = table.getColumnModel().getColumn(0);
  tcol.setCellRenderer((TableCellRenderer) new CustomTableCellRenderer());
  tcol = table.getColumnModel().getColumn(1);
  tcol.setCellRenderer((TableCellRenderer) new CustomTableCellRenderer());
  tcol = table.getColumnModel().getColumn(2);
  tcol.setCellRenderer((TableCellRenderer) 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.cyan);
  }
  else {
  cell.setBackground(Color.lightGray);
  }
  }
  return cell;
  }
  }
}

2 个答案:

答案 0 :(得分:1)

  

但我想只在年份栏(年份值)等于某个值时将青色设置为行

请勿使用单个渲染器。相反,您可以使用Table Row Rendering中的方法。

答案 1 :(得分:0)

您可以像在CustomTableCellRenderer类

中那样执行此操作
TableModel model = table.getModel();
String colYear = model.getColumnName(2);
int colYearValue = Integer.valueOf((String) model.getValueAt(row, 2));

if (colYearValue == 3) {
    cell.setBackground(Color.cyan);
} else {
    cell.setBackground(Color.lightGray);
}