根据列值更改JTable整行的背景颜色

时间:2015-07-23 11:13:50

标签: java swing jtable tablecellrenderer

所以我想做的是根据最后一列内的值改变每一行的颜色。

我已经找到了这个解决方案:Change Background Color of JTable效果非常好。

但另外我想在第四列达到与第二列相同的值时将行的颜色切换为绿色。

我使用了Cristian Marian的方法并编写了我自己的课程

    @Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
    Component comp = super.prepareRenderer(renderer, row, column);


        int second = (int) this.getModel().getValueAt(row, 1);
        int forth = (int) this.getModel().getValueAt(row, 3);
        int kat = Kategorie.getNumber((String) this.getModel().getValueAt(row, 2)); 
        if (kat > 0) {
            if (second == forth) {
                comp.setBackground(Color.GREEN);
            } else {
                comp.setBackground(Color.RED);
            }
        }

    return comp;
}

仍然只有每列中的最后一个单元格变为绿色而不是整个单元格。但是当我在行上计时时,整行会切换颜色

最后一列中的值被另一帧更改。

表格开头: http://i.stack.imgur.com/qIIVf.jpg

当最后一列中的值达到与第二列中相同的值时,它看起来像这样:

达到给定值后: http://i.stack.imgur.com/pSzU7.jpg

2 个答案:

答案 0 :(得分:4)

您的方法存在的问题是您使用getTable Cell RendererComponent,因此只有该单元格的颜色会发生变化。

我必须做类似的事情。根据列的值,我不得不为行着色。

我使用了扩展JTable和Override prepareRenderer的类

@Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
    Component comp = super.prepareRenderer(renderer, row, column);
    if (populated) {  //this if was just to make sure that I have data in my table
        /*
        *This piece makes the code ignore the rows that are selected as this approach messes up that blue color that selected rows get
        */
        int[] rows = this.getSelectedRows();
        boolean rowisSelected = false;

        for (int rowIndex : rows) {
            if (row == rowIndex) {
                rowisSelected = true;
                break;
            }
        }
        /*
        *And this is the part that does the coloring
        */
        if (!rowisSelected) {
            Integer status = Integer.parseInt((String) 
            int modelRow = convertRowIndexToModel(row);
            this.getModel().getValueAt(modelRow, Constants.HIDDEN_COLUMN));
            switch (status) {
            case 1:
                comp.setForeground(Color.BLACK);
                comp.setBackground(Color.WHITE);
                break;
            case 2:
                comp.setForeground(Color.LIGHT_GRAY);
                comp.setBackground(Color.WHITE);
                break;
            case 3:
                comp.setForeground(Color.BLACK);
                comp.setBackground(Constants.DOWNLOADED_COLOR);
                break;
            case 4:
                comp.setForeground(Color.LIGHT_GRAY);
                comp.setBackground(Constants.DOWNLOADED_COLOR);
                break;
            }
        }
    }
    return comp;
}

你的应该是这样的(没有选中的行):

@Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
    Component comp = super.prepareRenderer(renderer, row, column);
    int modelRow = convertRowIndexToModel(row);
    String second = this.getModel().getValueAt(modelRow, 1));
    String forth= this.getModel().getValueAt(modelRow, 3));
    if(second.equals(forth)){
        comp.setBackground(Color.GREEN);
    }
    return comp;
}

答案 1 :(得分:0)

我有另一个解决上述问题的方法。就我而言,我有一个包含10列的JTable。我只希望根据输入的Mark强调某个单元格行的子集。在下面附带的示例屏幕截图中,我输入了Mark 167并按下了Find All按钮。这样,细胞渲染器突出显示了细胞的子集。即,脚本否候选人标记成绩 enter image description here为了实现这一目标,我创建了一个单元格渲染器来扩展DefaultCellRenderer。我已经删除了一些与问题无关的代码,因此可能无法编译。尽管如此,您仍然可以了解问题的解决方案:

import java.awt.Component;
import java.awt.Color;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;

/*
 *
 * This class is the Color Renderer for the "Find All" Button.
 * It basically highlights all of the scripts with a certain color
 * This renderer is responsible Highlighting the JTable.
 * Based on the particular Mark that has been entered in the find all   
 * text field
 *
 *
 */

public class MarkSearchColorCellRenderer extends DefaultTableCellRenderer     
  implements ColorCellRenderer, GradeValidation
{
   public MarkSearchColorCellRenderer(int aMark, Color aColor)
   {
    the_Mark = aMark;
    theColor = aColor;
    }
    @Override
    public Component  getTableCellRendererComponent(JTable table, Object  
       value, boolean isSelected, boolean hasFocus, int row, int column)
    {

        Component cell = super.getTableCellRendererComponent(table,     
                            value, isSelected, hasFocus, row, column);

        setHorizontalAlignment(RIGHT);


        if ( column == 0 ) // script no column
        {
            //check the current Mark within this row
            //i.e. for this particular candidate
            Object curMark =  table.getValueAt(row, column+2);

            //highlight this cell a certain color if the
            //search mark has been found for this particular candidate
            highlightScripts(curMark, cell);
        }
        else if(column == 1) // Candidate No. Column
        {
            Object curMark =  table.getValueAt(row, column+1);

            highlightScripts(curMark, cell);
        }
        else if ( column == 2 ) // mark column
        {
             Object curMark = value;

             highlightScripts(curMark, cell);
        }
        else if (column == 3) // Grade Column
        {
             setHorizontalAlignment(LEFT);

             Object curMark =  table.getValueAt(row, column-1);

             highlightScripts(curMark, cell);
        }
        else if (column == 5) // script no column
        {
            Object curMark =  table.getValueAt(row, column+2);

            highlightScripts(curMark, cell);

        }
        else if( column == 6) // Candidate No. Column
        {
           Object curMark =  table.getValueAt(row, column+1);

           highlightScripts(curMark, cell);
        }
        else if ( column == 7) // mark column
        {
            Object curMark = value;

            highlightScripts(curMark, cell);

         }
         else if ( column == 8) // Grade Column
         {
            setHorizontalAlignment(LEFT);

             Object curMark =  table.getValueAt(row, column-1);

             highlightScripts(curMark, cell);

         }
         else
         {
             // Should never arrive here.
             // If it does, then you've rendered a column that may not
             // function with this class
             // therefore, I'm going to exit the program

              //System.exit(0);
         }

         table.repaint();

         return cell;

     } // end getTableCellRendererComponent()

     // Change the color of this cell if the aValue matches
     // the value within the particular cell
     private void highlightScripts(Object aValue, Component aCell)
     {
         Object value = aValue;
         Component cell = aCell;

         if ( value != null )
         {
             if (value instanceof Integer )
             {
                Integer amount = (Integer) value;

                if( amount.intValue() == the_Mark )
                {
                    cell.setBackground( theColor );

                 }
                 else
                 {
                     cell.setBackground( Color.white );

                 }
             }
         }
         else
         {
            cell.setBackground( Color.white );
         }
      }// end highlightScripts()

}//end class

/* * * Inside the "Find All" button listener you would attach the * MarkSearchColorCellRenderer to selected JTable columns. * A snippet of the code is as follows: * */ // select a color Color myMarkColor = new Color(226,182,90); // the mark to search Integer markToSearch = new Integer(find_mark_jTextField.getText()); //an instance of the class MarkSearchColorCellRenderer (outlined above) MarkSearchColorCellRenderer my_MarkSearch_CellRenderer = new MarkSearchColorCellRenderer( markToSearch.intValue(),myMarkColor); /* * * Get the all the Table columns of the JTable on which you wish to assign * the particular cell renderer. In my example I have 8 table column's * that I wish to assign the cell renderer * i.e. Script, Candidate, Mark, Grade Script, Candidate, Mark, Grade * * On looking at the screenshot I've ignored the monitor column (check box) */ TableColumn script_column_100_A = first_100_Table.getColumnModel().getColumn(0); TableColumn candidate_column_100_A = first_100_Table.getColumnModel().getColumn(1); TableColumn mark_column_100_A = first_100_Table.getColumnModel().getColumn(2); TableColumn grade_column_100_A = first_100_Table.getColumnModel().getColumn(3); TableColumn script_column_100_B = first_100_Table.getColumnModel().getColumn(5); TableColumn candidate_column_100_B = first_100_Table.getColumnModel().getColumn(6); TableColumn mark_column_100_B = first_100_Table.getColumnModel().getColumn(7); TableColumn grade_column_100_B = first_100_Table.getColumnModel().getColumn(8); /* * * assign the MarkSearchColorCellRenderer to each of the choosen table column's. * * i.e. Script, Candidate, Mark, Grade Script, Candidate, Mark, Grade * */ script_column_100_A.setCellRenderer(my_MarkSearch_CellRenderer ); script_column_100_A.setCellRenderer(my_MarkSearch_CellRenderer ); candidate_column_100_A.setCellRenderer(my_MarkSearch_CellRenderer ); mark_column_100_A.setCellRenderer(my_MarkSearch_CellRenderer ); grade_column_100_A.setCellRenderer(my_MarkSearch_CellRenderer ); script_column_100_B.setCellRenderer(my_MarkSearch_CellRenderer ); candidate_column_100_B.setCellRenderer(my_MarkSearch_CellRenderer ); mark_column_100_B.setCellRenderer(my_MarkSearch_CellRenderer ); grade_column_100_B.setCellRenderer(my_MarkSearch_CellRenderer ); this.repaint();