我正在尝试使JTable
标题的背景具有渐变。
使用以下代码可以正常工作:
String[] colName = new String[] { "#", "Location", "Name" ,"Source", "System", "Hits", "Current", "Time" };
Object[][] products = new Object[][] {
};
dtm = new DefaultTableModel(products, colName) {
@Override
public boolean isCellEditable(int row, int column) {
//all cells false
return false;
}
};
table = new JTable( dtm );
table.setRowHeight(32);
table.getTableHeader().setReorderingAllowed(false);
table.setDefaultRenderer(Object.class, new VisitorRenderer());
table.setFont(new java.awt.Font("Tahoma", Font.PLAIN, 12));
table.getColumnModel().getColumn(0).setMinWidth(5);
table.getColumnModel().getColumn(1).setMinWidth(50);
table.getColumnModel().getColumn(2).setMinWidth(5);
table.getColumnModel().getColumn(3).setMinWidth(5);
table.getColumnModel().getColumn(4).setMinWidth(5);
table.getColumnModel().getColumn(5).setMinWidth(3);
table.getColumnModel().getColumn(6).setMinWidth(230);
table.getColumnModel().getColumn(7).setMinWidth(3);
final JTableHeader header = table.getTableHeader();
header.setPreferredSize(new Dimension(100, 37));
header.setDefaultRenderer(new DefaultTableCellHeaderRenderer() {
private Object selectedColumn;
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
GradientPaint gp = new GradientPaint(0, 0,
new java.awt.Color(237, 237, 237), 0, getHeight(),
new java.awt.Color(222, 222, 222));
g2d.setPaint(gp);
g2d.fillRect(0, 0, getWidth(), getHeight());
}
@Override
public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
DefaultTableCellHeaderRenderer rendererComponent = (DefaultTableCellHeaderRenderer) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if (selectedColumn == value) {
rendererComponent.setBorder(BorderFactory.createCompoundBorder(rendererComponent.getBorder(), BorderFactory.createLineBorder(Color.red, 1)));
rendererComponent.setHorizontalAlignment(SwingConstants.LEFT);
} else {
rendererComponent.setBorder(BorderFactory.createCompoundBorder(rendererComponent.getBorder(), BorderFactory.createEmptyBorder(0, 5, 0, 0)));
rendererComponent.setHorizontalAlignment(SwingConstants.CENTER);
}
if (column == 0) {
rendererComponent.setForeground(header.getForeground());
} else {
rendererComponent.setForeground(header.getForeground());
}
return rendererComponent;
}
});
但是由于某种原因,我看不到我的边框和文本,似乎文本也应用了渐变?
我想在我的列之间设置黑色文本和彩色边框。有任何想法吗?