简体   繁体   中英

change background color of row in jtable after selection

I am trying to create a TableCellRenderer which changes the background of row. I am overriding the prepareRenderer , it changes the background of row on selection but as soon as I change the selection the default background color(white) is set to previous selected row and newer row gets the background color(light grey).

Here is my code:

 final JTable table = new JTable(model) { @Override public Component prepareRenderer(TableCellRenderer renderer,int row,int column) { Component comp=super.prepareRenderer(renderer,row, column); int modelRow=convertRowIndexToModel(row); if(!isRowSelected(modelRow)) comp.setBackground(Color.WHITE); else comp.setBackground(Color.LIGHT_GRAY); return comp; } }; 

My output screen:

在此输入图像描述

I want to do like this:

在此输入图像描述

Try this:

table.setDefaultRenderer(Object.class, new TableCellRenderer(){
        private DefaultTableCellRenderer DEFAULT_RENDERER =  new DefaultTableCellRenderer();


            @Override
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                Component c = DEFAULT_RENDERER.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
                //table.setBackground(Color.YELLOW);
                 //table.setSelectionBackground(Color.YELLOW);
                if(isSelected){
                    c.setBackground(Color.YELLOW);
                }else{
                if (row%2 == 0){
                    c.setBackground(Color.WHITE);

                }
                else {
                    c.setBackground(Color.LIGHT_GRAY);
                }     }

                return c;
            }

        });

For your requirement you can do the following:

IN your model keep a hidden column of flag values. Assume that your hidden column is 5 column and you can code as below:

final JTable table = new JTable(model)
    {
            @Override
        public Component prepareRenderer(TableCellRenderer renderer,int row,int column)
        {
            Component comp=super.prepareRenderer(renderer,row, column);
           int modelRow=convertRowIndexToModel(row);
           if((Boolean)getValueAt(row,5))
               comp.setBackground(Color.LIGHT_GRAY);
           else
               comp.setBackground(Color.WHITE);
           return comp;
        }
    };

Your flag values contain the Boolean object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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