jTable Cell background color

后端 未结 3 1202
独厮守ぢ
独厮守ぢ 2021-01-24 21:02

I am trying to color a cell of a jTable using the renderers, but they are not working well, as they lag the table and make it impossible to see. here\'s my code:



        
3条回答
  •  不要未来只要你来
    2021-01-24 21:12

    First of all variable names should NOT start with an upper case character. Some of your variables are correct, others are not. Be consistent!!!

    I've tried to color a cell of a jTable using the renderers, but they are useless they lag the table and make it impossible to see.

    Just because you don't understand the concept does not make it useless. The problem is with your code, not the concept of renderers.

    Your posted code makes no sense. You can't set the color of an individual cell. The color is determined when the cell is renderer, which is why you need to use a renderer.

    it colors the table completely

    Yes, once you set the background of the renderer all cells in the future will use that color. You need to reset the color to its default before rendering each cell

    the background must be red just in case it's a number AND it's higher than 24,

    Then do a positive check and forget about all those negative checks.

    Using all the above suggestions you might have a renderer something like:

    class ColorRenderer extends DefaultTableCellRenderer
    {
        @Override
        public Component getTableCellRendererComponent(
            JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
        {
            super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    
            if (isSelected)
                setBackground( table.getSelectionBackground() );
            else
            {
                setBackground( table.getBackground() );
    
                try
                {
                    int number = Integer.parseInt( value.toString() );
    
                    if (number > 24)
                        setBackground( Color.RED );
                }
                catch(Exception e) {}
            }
    
            return this;
        }
    }
    

提交回复
热议问题