我试过了:
table.getTableHeader().setBackground(Color.BLACK);
Try this:
table.getTableHeader().setOpaque(false);
then set the background of jtable
header
table.getTableHeader().setBackground(Color.BLACK);
It works for me. Here's 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 doesn't help you, then I suggest that you create and post your own SSCCE so that we can see what's wrong.
I recommend you to 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);
}
The table header also uses a renderer component, like table cells.
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 a dynamic color, you can also set the color in the constructor of the renderer.
Solved it. In NetBeans:
Also the graphics of the whole project changed appearance.
private void table_head_color(JTable table_name){
DefaultTableCellRenderer head_render = new DefaultTableCellRenderer();
head_render.setBackground(new Color(204,153,255)); table_name.getTableHeader().setDefaultRenderer(head_render);
//to call above method //table_head_color(""write table name"); }
This question is old but I have the right answer, I guess...
All that you have to do is set opaque to true
.
eg
yourComponent.setOpaque(true);
I hope this can help someone in the future.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.