How to get full highlighting (with border) on JTable Renderer
There is a common method when using JTable TableCellRenderers for setting the background and foreground when the cell is selected. Here is an example question that was asked:
Why does my Java custom cell renderer not show highlighting when the row/cell is selected?
This solution is lacking one thing ... the border around the cell. (Note I am not asking about a border around the row, as was asked here.) The border should highlight when the cell is selected. It is not acceptable to just create your own Border, and set it, because the border you create may not fit in with the Look & Feel.
I've successfully got the border by initializing a default renderer, and then scav开发者_Go百科enging it for its border, as follows:
private final DefaultTableCellRenderer defTblRend = new DefaultTableCellRenderer();
private final JComponent renderer = new ComplexCell(); // Whatever object type extends JComponent
@Override public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row,
int column)
{
// ... Set values on "renderer" object here ...
renderer.setBackground(isSelected ? table.getSelectionBackground() : table.getBackground());
renderer.setForeground(isSelected ? table.getSelectionForeground() : table.getForeground());
renderer.setOpaque(!renderer.getBackground().equals(table.getBackground()));
JComponent comp = (JComponent)defTblRend.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
renderer.setBorder(comp.getBorder());
return renderer;
}
Is there a better way?
You might be able to use the UIManager. See UIManager Defaults. "Table.focusCellHighlightBorder" would appear to be the property you want.
ADDED BY ORIGINAL POSTER:
Here is the solution I came up with based on camickr's info. Optimizations/cleanup welcome.
Set up static borders so they are available wherever you need them (I put them in a class called "UiUtils"):
public static final Border focusedCellBorder = UIManager.getBorder("Table.focusCellHighlightBorder"); public static final Border unfocusedCellBorder = createEmptyBorder(); private static Border createEmptyBorder() { Insets i = focusedCellBorder.getBorderInsets(new JLabel()); return BorderFactory.createEmptyBorder(i.top, i.left, i.bottom, i.right); }
Renderer
@Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { // [... set component values here ...] label.setBorder(hasFocus ? UiUtils.focusedCellBorder : UiUtils.unfocusedCellBorder); return label; }
精彩评论