i\'m currently building a little JTable, and want to highlight the column header (and row headers - the row-header part is actually working) when a cell is selected to make
A slight variant: as I read the question, the main problem is the header not updating on column selection change. Having a custom header listen to row selection changes doesn't help much for that scenario.
In fact, a JTableHeader already is listening to the ColumnModel and the model's change notification includes selection changes. Only the columnSelectionChange method is intentionally implemented to do nothing:
// --Redrawing the header is slow in cell selection mode.
// --Since header selection is ugly and it is always clear from the
// --view which columns are selected, don't redraw the header.
A custom header can simply implement to repaint (here lazy me does it in the table's factory method just to spare me the wiring to the table, you can easily make it a stand-alone class :-).
final JTable table = new JTable(new AncientSwingTeam()) {
@Override
protected JTableHeader createDefaultTableHeader() {
// subclassing to take advantage of super's auto-wiring
// as ColumnModelListener
JTableHeader header = new JTableHeader(getColumnModel()) {
@Override
public void columnSelectionChanged(ListSelectionEvent e) {
repaint();
}
};
return header;
}
};
table.setCellSelectionEnabled(true);
table.getTableHeader().setDefaultRenderer(new ColumnHeaderRenderer());
Also tweaked Mad's renderer a bit, using table api:
/**
* Slightly adjusted compared to @Mad
* - use table's selectionBackground
* - use table's isColumnSelected to decide on highlight
*/
public static class ColumnHeaderRenderer extends DefaultTableCellHeaderRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean selected,
boolean focused, int row, int column) {
super.getTableCellRendererComponent(table, value, selected, focused, row, column);
if (table.isColumnSelected(column)) {
setBackground(table.getSelectionBackground());
}
return this;
}
}
As to the observation:
always says isSelected is false
The reason is a slight quirk in BasicTableHeaderUI:
ui.selected != columnModel.selected
uiSelected is the column which will be accessible to keybindings - if the laf supports it and the header is focusOwner. Doesn't really make sense to me, but fully defining the semantics of ui and columnModel selection fell into the excitement about the new babe fx, that is got forgotten ;-)