How to change background color of JTable header?

I tried:

table.getTableHeader().setBackground(Color.BLACK); 

Does not work.

EDIT: This code does not work only in my project. Works in other projects. Maybe I changed a property that stops the color change. Or maybe NetBeans has a property that preserves default colors. I noticed something else. The title color in my project shines differently. In the examples where the color changes, I see different graphs.

EDIT 2: Something else. I noticed that the buttons also will not change color. There must be something in common. Hope this helps. Unfortunately, SSCCE will not work in this case, because I cannot recreate the problem. I definitely use the correct component names.

+7
source share
5 answers

I decided. In NetBeans:

  • Right click on project name
  • The properties
  • Application - Desktop Application
  • Look and feel: select "Java Default" (does not work with System Default).
  • Remember to clean and rebuild before starting the project

Also, the graphics of the entire project changed the look.

+1
source

This works for me. Here is my SSCCE :

 import java.awt.*; import javax.swing.*; import javax.swing.table.*; public class TableHeaderBackground { public static void main(String[] args) { Integer[][] data = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; String[] cols = {"A", "B", "C"}; JTable table = new JTable(data, cols); JTableHeader header = table.getTableHeader(); header.setBackground(Color.black); header.setForeground(Color.yellow); JOptionPane.showMessageDialog(null, new JScrollPane(table)); } } 

If this does not help you, I suggest you create and publish your own SSCCE so that we can see what is wrong.

+11
source

Try it... . Table.getTableHeader () setOpaque (false);

then set the jtable header background

table.getTableHeader () setBackground (Color.BLACK) ;.

+7
source

I recommend you do this:

 DefaultTableCellRenderer headerRenderer = new DefaultTableCellRenderer(); headerRenderer.setBackground(new Color(239, 198, 46)); for (int i = 0; i < myJTable.getModel().getColumnCount(); i++) { myJTable.getColumnModel().getColumn(i).setHeaderRenderer(headerRenderer); } 
+5
source

The table header also uses a rendering component, such as a table cell.

Look at this:

 table.getTableHeader().setDefaultRenderer(new DefaultTableRenderer(){ { // you need to set it to opaque setOpaque(true); } @Override public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected, final boolean hasFocus, final int row, final int column) { // set the background setBackground(yourDesiredColor); } }); 

If you do not need dynamic color, you can also set the color in the renderer constructor.

+3
source

All Articles