JTable row hightlighter based on value from TableCell

how to set Alignment for TableCell into prepareRenderer,

This should NOT be done in the prepareRenderer code. This property should be set in the renderer for the class or for the column because it only applies to a specific class or renderer. Instead use:

table.setPreferredScrollableViewportSize(table.getPreferredSize());
DefaultTableCellRenderer stringRenderer = (DefaultTableCellRenderer)table.getDefaultRenderer(String.class);
stringRenderer.setHorizontalAlignment( SwingConstants.CENTER );

For the highlighting code I used code that assumes that the dealld value is unique for a given set of transactions:

        private Map<Object, Color> rowColor = new HashMap<Object, Color>();
        private Color nextColor = Color.ORANGE;

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

            if (isRowSelected(row)) return c;

            Object value = table.getValueAt(row, 7);
            Color background = rowColor.get(value);

            if (background != null)
            {
                c.setBackground( background );
            }
            else
            {
                rowColor.put(value, nextColor);
                c.setBackground( nextColor );
                nextColor = (nextColor == Color.ORANGE) ? Color.YELLOW : Color.ORANGE;
            }

            return c;
        }

Note: It won’t work if sorting is required.

Here is another approach that should work even if sorting is required (but I didn’t test it with sorting);

        @Override
        public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
            Component c = super.prepareRenderer(renderer, row, column);
            JComponent jc = (JComponent) c;
            if (!isRowSelected(row))
            {
                c.setBackground(getRowBackground(row));
            }

            return c;
        }

        private Color getRowBackground(int row)
        {
            boolean isDark = true;

            Object previous = getValueAt(0, 7);

            for (int i = 1; i <= row; i++)
            {
                Object current = getValueAt(i, 7);

                if (! current.equals(previous))
                {
                    isDark = !isDark;
                    previous = current;
                }
            }

            return isDark ? Color.ORANGE : Color.YELLOW;
        }

Leave a Comment