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

前端 未结 3 1292
别那么骄傲
别那么骄傲 2020-12-10 15:58

I have a basic swing JTable and the requirement is that when clicked on any cell, the entire row should be highlighted, and also that the cell which was clicked should be a

相关标签:
3条回答
  • 2020-12-10 16:11

    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.

    0 讨论(0)
  • 2020-12-10 16:15

    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.

    0 讨论(0)
  • 2020-12-10 16:28

    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.

    0 讨论(0)
提交回复
热议问题