Search code examples
javawindowsjtablelook-and-feeljtableheader

How to change the primary color of a JTableHeader in Windows LookAndFeel?


I have already created an similar post where I asked that question as EDIT. But I do not think many people will see it like that. My question is, how I change the background color of a JTableHeader (So the Colors of the columns). I know that normaly

table.getHeader().setBackground(Color.blue);

should work, but this does not work when I set the LookAndFeel on Windows look and feel. com.sun.java.swing.plaf.windows.WindowsLookAndFeel


Solution

  • It is recommended to use the below look and fee.

    UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
    

    I provide below the complete runnable sample code where you can see the Blue color table header.

    import javax.swing.*;
    import java.awt.*;
    
    public class TableHeaderExample {
      private JFrame jFrame;
    
      public TableHeaderExample() {
        jFrame = new JFrame();
      }
    
      private void setLookAndFeel() {
        try {
          UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
          //Do not use below.
    //      UIManager.setLookAndFeel(
    //              "com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    
        } catch (Exception ex) {
          ex.printStackTrace();
        }
      }
    
      public void createTableWithColorHeader() {
        setLookAndFeel();
        String data[][] = {{"Sambit", "23", "1000"}, {"John", "25", "200"}};
        String column[] = {"EMP NAME", "EMP AGE", "EMP SALARY"};
        JTable jTable = new JTable(data, column);
        jTable.getTableHeader().setBackground(Color.blue);
        jTable.setBounds(30, 40, 200, 300);
        JScrollPane sp = new JScrollPane(jTable);
        jFrame.add(sp);
        jFrame.setSize(300, 400);
        jFrame.setVisible(true);
        jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      }
    
    
      public static void main(String[] args) {
        TableHeaderExample example = new TableHeaderExample();
        example.createTableWithColorHeader();
      }
    }
    

    See below the image. enter image description here

    Also refer to the following link. http://leo.ugr.es/elvira/devel/Tutorial/Java/uiswing/misc/plaf.html To quote one line is

    IManager.getCrossPlatformLookAndFeelClassName() Returns the string for the one look-and-feel guaranteed to work -- the Java Look & Feel. UIManager.getSystemLookAndFeelClassName() Specifies the look and feel for the current platform. On Win32 platforms, this specifies the Windows Look & Feel