5

I want to change the background color of particular table header. In my appliaction I have to set header color Red on the current month. enter image description here My Code is here::

     jTable1.getTableHeader().
    setDefaultRenderer(
    new DefaultTableHeaderCellRenderer());



  @Override
  public Component getTableCellRendererComponent(JTable table, Object value,
          boolean isSelected, boolean hasFocus, int row, int column) {
    super.getTableCellRendererComponent(table, value,
            isSelected, hasFocus, row, column);
    JTableHeader tableHeader = table.getTableHeader();

    if(column==1)
    tableHeader.setBackground(Color.red);


    return this;
  }

this make all the header color's red. Please give me some suggestion. Thanks in advance.

Aritra
  • 163
  • 4
  • 18

1 Answers1

6

The infamous color memory of DefaultTableCellRenderer :-) You have to

  • set the background color always: that is for both normal and highlighted state
  • do so before calling super

something like:

  @Override
  public Component getTableCellRendererComponent(JTable table,
        Object value, boolean isSelected, boolean hasFocus, int row,
        int column) {
      if (myHighlightCondition) {
          setBackground(Color.RED);
      } else {
          setBackground(null);
      }
     super.getTableCellRendererComponent(table, value, isSelected, hasFocus,
           row, column);
     return this;
  }

For more details (and why that's needed) see a How do I correctly use custom renderers to paint specific cells in a JTable?

Community
  • 1
  • 1
kleopatra
  • 51,061
  • 28
  • 99
  • 211
  • +1 to this answer and the linked answer. Now that is something worth remembering to avoid loosing heaps of time the next time I am working with tables – Robin Mar 23 '12 at 12:38