简体   繁体   English

如何在jtable中动态设置行的颜色?

[英]How to set color of rows dynamically in jtable?

I have been seen many articles but I don't understand how to do it! 我见过很多文章,但我不知道该怎么做!

I want to change the color of some rows in JTable . 我想更改JTable中某些行的颜色。 The table has 3 columns: a, b and c. 该表有3列:a,b和c。

The rules 规则

  1. If the value of a<=b the color of the entire row must be red 如果a <= b的值,则整个行的颜色必须为红色
  2. If the value of a>=c the color of the entire row must be yellow 如果a> = c的值,则整行的颜色必须为黄色
  3. in default the color of row must be blue. 默认情况下,行的颜色必须为蓝色。

Try the following code 试试下面的代码

public class IconifiedRenderer extends JLabel implements TableCellRenderer {
public IconifiedRenderer() {
}
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    JLabel label = this;
    int cellValueA=-1;
    int cellValueB=-1;
    int cellValueC=-1;
    try {
        setOpaque(true);
        label.setText(String.valueOf(value));
       try {
            cellValueA = Integer.parseInt(String.valueOf( table.getValueAt(row, 0))); //0th for A
        } catch (ArrayIndexOutOfBoundsException aa) {
            //ignore
            cellValueA=-1;
        }
       try {
            cellValueB = Integer.parseInt(String.valueOf( table.getValueAt(row, 1))); //1th for A
        } catch (ArrayIndexOutOfBoundsException aa) {
            //ignore
            cellValueB=-1;
        }
       try {
            cellValueC = Integer.parseInt(String.valueOf( table.getValueAt(row, 2))); //2th for A
        } catch (ArrayIndexOutOfBoundsException aa) {
            //ignore
            cellValueC=-1;
        }
       label.setBackground(Color.BLUE);

       if(cellValueA<=cellValueB){
           label.setBackground(Color.RED);
       }
       if(cellValueA>=cellValueC){
           label.setBackground(Color.YELLOW);
       }
    } catch (Exception ex) {
        // no need to handle
    }
    return label;
}

Add this render class and set the render on you table column 添加此渲染类并在表列上设置渲染

    jTable1.getColumnModel().getColumn(0).setCellRenderer(new IconifiedRenderer());
    jTable1.getColumnModel().getColumn(1).setCellRenderer(new IconifiedRenderer());
    jTable1.getColumnModel().getColumn(2).setCellRenderer(new IconifiedRenderer());

It will show your table like this... 它会像这样显示您的桌子...

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM