JFormDesigner / FlatLaf

FlatLaf - Swing Look and Feel (with Darcula/IntelliJ themes support)
https://www.formdev.com/flatlaf/
Apache License 2.0
3.42k stars 272 forks source link

BooleanRenderer provided by JTable doesnt respect striped background if using Table.alternateRowColor #515

Closed ijabz closed 2 years ago

ijabz commented 2 years ago

The default String renderer provided by JTable works with Table.alternateRowColor but the Boolean Renderer does not. Not sure if would consider this a bug in JTable or something Flatlaf could resolve in JTableUI, but my solution was to make a copy of JTable.BooleanRenderer to create new renderer with extra code in getTableCellRendererComponent()

import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.plaf.UIResource;
import javax.swing.table.TableCellRenderer;
import java.awt.*;

public class StripedBooleanRenderer extends JCheckBox implements TableCellRenderer, UIResource
{
    private static final Border noFocusBorder = new EmptyBorder(1, 1, 1, 1);

    public StripedBooleanRenderer() {
        super();
        setHorizontalAlignment(JLabel.CENTER);
        setBorderPainted(true);
    }

    public Component getTableCellRendererComponent(JTable table,
                                                   Object value,
                                                   boolean isSelected,
                                                   boolean hasFocus,
                                                   int row,
                                                   int column)
    {
        if (isSelected)
        {
            setForeground(table.getSelectionForeground());
            super.setBackground(table.getSelectionBackground());
        }
        else
        {
            setForeground(table.getForeground());
            if(row % 2 ==0)
            {
                setBackground(table.getBackground());
            }
            else
            {
                setBackground(UIManager.getColor("Table.alternateRowColor"));
            }
        }
        setSelected((value != null && ((Boolean)value).booleanValue()));

        if (hasFocus)
        {
            setBorder(UIManager.getBorder("Table.focusCellHighlightBorder"));
        } else
        {
            setBorder(noFocusBorder);
        }
        return this;
    }
}

and then in subclass of JTable have
public TableCellRenderer getDefaultRenderer(Class<?> columnClass)
{
    if(columnClass==Boolean.class)
    {
        return new StripedBooleanRenderer();
    }
    return super.getDefaultRenderer(columnClass);
}
DevCharly commented 2 years ago

That's a bug in Swing. Occurs also in core Lafs.