Swing JTable - Highlight selected cell in a different color from rest of the selected row?

自闭症网瘾萝莉.ら 提交于 2019-11-29 06:52:46

Try this:

jtable.setCellSelectionEnabled(true);

Then in the getTableCellRendererComponent

if (table.isCellSelected(row, column))
    setForeground(Color.red);
else if (table.isRowSelected(row))
    setForeground(Color.green);
else if (table.isColumnSelected(column))
    setForeground(Color.blue);
else
    setForeground(Color.black);

That will render the selected cell in red, the rest of the row in green, and the rest of the column in blue. Note: cell selection requires the selection model be single, other selection models may cause unpredictable behaviors.

But that did not seem to work (entire row was highlighted in red).

You need to check the "hasFocus" variable, not the "isSelected" variable.

Another option instead of creating mulutiple custom renderers (in case you table has columns of different class types) is to use the Table Row Renderering approach.

You would need to turn row selection off and cell selection on for the table. Then find a way to go back and highlight the row if needed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!