如何使用行和列索引在JTable中设置特定单元格的颜色(TableCellRenderer)

时间:2015-01-30 11:32:03

标签: java swing jtable tablecellrenderer

我创建了以下TableCellRenderer来设置JTable中特定单元格的颜色。问题是它设置了整个列的颜色。如何定义行?

package run;

import java.awt.Color;
import java.awt.Component;
import java.awt.Font;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;

public class test4 {


    /**
     * @param args
     */
    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI(); 
            }
        });     
    }

    private static void createAndShowGUI() {
        gtest t = new gtest("");
        t.pack();
        t.setVisible(true);
        t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        t.setLocationRelativeTo(null);
    }


}

class gtest extends JFrame
{

    private static JTable table;
    private int index;

    public gtest(String title)
    {
        Object cols[] = {"A","B"};
        double data[][] = {{2,10},{5,20},{20,11}};
        table = new JTable(3,2);

        for (int i = 0; i< data.length; i++)
        {
            for (int j=1; j<cols.length; i++)
            {
                double val = data[i][j] + 5*data[i][j]-1;
                table.getColumnModel().getColumn(j).setCellRenderer(new ColorRenderer());
                // here I want to put a Thread.sleep or something similar to
                // visualize the filling out of a table
            }
        }
        add(table);

    }
}

class ColorRenderer extends JLabel implements TableCellRenderer  {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public ColorRenderer() {
        setOpaque(true);
    }

    public Component getTableCellRendererComponent(
                            JTable table, Object value,
                            boolean isSelected, boolean hasFocus,
                            int row, int column) {
      setText(value.toString());
      setFont(new Font("SansSerif", Font.PLAIN, 10));
      setBackground(Color.lightGray);
      return this;
    }
}

1 个答案:

答案 0 :(得分:3)

TableCellRenderer设置为整列,只更改一些行,需要在getTableCellRendererComponent()方法中实现行号验证。

例如rowIndex = 1的chage颜色:

setBackground(row == 1 ? Color.lightGray : table.getBackground());

阅读TableCellRenderer的文档。