How to set color to a certain row if certain conditions are met using java?

后端 未结 3 1438
孤城傲影
孤城傲影 2020-11-27 07:42

I have A jtable. (tablesummary). one of it\'s column is EXPIRY. i want to highlight the row with the client whose expiry date already lapsed on the current date..

i

3条回答
  •  甜味超标
    2020-11-27 08:11

    In the following link, you can find an example of the action you want to do: http://www.roseindia.net/java/example/java/swing/SadingRows.shtml

    You have to override prepareRenderer() on JTable and add the backgroundColor on the Component that gets returned.

    PS: for future reference, it would be easier if you would include more code. The definition of your rowrenderer =)

    EDIT

    Instead of your normal JTable table = new JTable(model) declaration, use the following (change the logic in the prepareRenderer method if you want something else than an alternating color):

    JTable table = new JTable(model) {
        public Component prepareRenderer(TableCellRenderer renderer, int Index_row, int Index_col) {
            // get the current row
            Component comp = super.prepareRenderer(renderer, Index_row, Index_col);
            // even index, not selected
            if (Index_row % 2 == 0 && !isCellSelected(Index_row, Index_col)) {
                comp.setBackground(Color.lightGray);
            } else {
                comp.setBackground(Color.white);
            }
            return comp;
        }
    };
    

提交回复
热议问题