Question

I want to change the font for the header of the selected column on JTable. I tried to do that on my ColumnHeaderRenderer as follow :

public class ColumnHeaderRenderer extends JLabel implements TableCellRenderer {

public ColumnHeaderRenderer(JTable table) {
    JTableHeader header = table.getTableHeader();
    setOpaque(true);
    setBorder(BorderFactory.createEtchedBorder());
    setHorizontalAlignment(CENTER);
    setForeground(header.getForeground());
    setBackground(header.getBackground());
    setFont(header.getFont());
    setPreferredSize(new Dimension(0, 25));

}

public Component getTableCellRendererComponent(JTable table, Object value,
        boolean isSelected, boolean hasFocus, int row, int column) {

    Color bg = UIManager.getColor("TableHeader.background");
    int selectedColumn = table.getSelectedColumn();
    if (selectedColumn == column){
        bg = new Color(107, 142, 35);
        setFont(getFont().deriveFont(Font.BOLD));// !!!!trying to do it here!!!!
    }
    setBackground(bg);
    setText(value.toString());
    return this;
}

}

But as result all column headers font is changed. So how can only change it for the selected column ?

Was it helpful?

Solution

You need to reset the values

if (selectedColumn == column){
    bg = new Color(107, 142, 35);
    setFont(getFont().deriveFont(Font.BOLD));// !!!!trying to do it here!!!!
} else {
    setFont(UIManager.getFont("TableHeader.font"));
}

Renders are a shared resource, so all the headers share the same render. This means if you change the state of the renderer from one pass to another, the next element rendered with the rendering will gain all the properties you used previously...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top