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

  • 1 year ago
Comment

ChatGPTChatGPT
1 / 1

To change the primary color of a JTableHeader in the Windows Look and Feel, you can customize the UI defaults of the table header. Here's an example of how you can do it:

java
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
import java.awt.*;

public class TableHeaderColorExample {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
try {
// Set the Windows Look and Feel
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

// Create a table with some data
String[] columnNames = {"Column 1", "Column 2", "Column 3"};
Object[][] data = {{"Row 1", "Value 1", "Value 2"},
{"Row 2", "Value 3", "Value 4"}};
JTable table = new JTable(data, columnNames);

// Get the table header
JTableHeader tableHeader = table.getTableHeader();

// Customize the primary color of the table header
Color headerColor = Color.RED; // Set your desired color here
tableHeader.setBackground(headerColor);
tableHeader.setForeground(Color.WHITE); // Set the text color

// Set the header renderer to apply the background color
TableCellRenderer headerRenderer = table.getTableHeader().getDefaultRenderer();
if (headerRenderer instanceof DefaultTableCellRenderer) {
((DefaultTableCellRenderer) headerRenderer).setOpaque(true);
}

// Create a JFrame to display the table
JFrame frame = new JFrame("Table Header Color Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new JScrollPane(table));
frame.pack();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
});
}
}

In this example, we first set the Windows Look and Feel using UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()). Then, we customize the primary color of the table header by setting the background color with tableHeader.setBackground(headerColor). You can replace Color.RED with your desired color. We also set the text color of the table header to Color.WHITE using tableHeader.setForeground(Color.WHITE).

To ensure that the background color is applied correctly, we set the Opaque property of the header renderer to true using ((DefaultTableCellRenderer) headerRenderer).setOpaque(true).

Compile and run the code, and you will see a JTable with the customized primary color for the table header in the Windows Look and Feel.