java ,swing, jtable ,设置单元格背景色

package jetsennet.install.util;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;

import java.util.ArrayList;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;

class EvenOddRenderer extends DefaultTableCellRenderer {

private static final long serialVersionUID = 1L;
private List<String[]> positioins;

public EvenOddRenderer(List<String[]> _positioins){
this.positioins = _positioins;
}

public Component getTableCellRendererComponent(JTable table, Object value,boolean isSelected, boolean hasFocus,
int row, int col) {

for(int i=0; i<table.getRowCount(); i++){
if (row == i){
this.setBackground(Color.white);
}
}
for(String[] rowAndCol : this.positioins){
int _row= Integer.valueOf(rowAndCol[0]);
int _col= Integer.valueOf(rowAndCol[1]);

if( _row == row && _col == col) {
            this.setBackground(Color.yellow);
     }
}
        this.setText(value.toString());
        return this;
}
}
public class ResizeTable {

public static void main(String args[]) {

final String columnNames[] = { "#", "English", "Roman" };
final Object rowData[][] = { { "1", "one",  "I" },{ "2", "two",  "II" }, { "4", "tahree", "III" },{ "3", "three", "III" },{ "5", "thasdfree", "III" }};
final JTable table = new JTable(rowData, columnNames);
JScrollPane scrollPane = new JScrollPane(table);

   //坐标值
String [] arr0= {"1","1"};
    String [] arr1= {"1","0"};
    String [] arr2= {"0","2"};
    String [] arr3= {"2","2"};
    String [] arr4= {"3","2"};
    List<String[]> _list= new ArrayList<String[]>();
    _list.add(arr0);
    _list.add(arr1);
    _list.add(arr2);
    _list.add(arr3);
    _list.add(arr4);
    EvenOddRenderer tablecellRender = new EvenOddRenderer(_list);
    table.setDefaultRenderer(Object.class,tablecellRender);   

JFrame frame = new JFrame("Resizing Table");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setBounds(400, 200, 600, 200);
frame.setVisible(true);
}
}

你可能感兴趣的:(java,swing,jtable)