How to change background color of an edited cell in JTable?

后端 未结 1 1258
醉话见心
醉话见心 2021-01-22 20:37

I searched everywhere but I still can\'t seem to find an answer to my question. I\'ve read all about cell renderers and cell editors but still no idea... I have a JTable, and I

相关标签:
1条回答
  • 2021-01-22 20:58

    First, get the table's default selection background color:

    Color color = UIManager.getColor("Table.selectionBackground");
    

    Second, override prepareEditor(), as shown in this example, and set the background color of the editor component to match:

    @Override
    public Component prepareEditor(TableCellEditor editor, int row, int col) {
        Component c = super.prepareEditor(editor, row, col);
        c.setBackground(color);
        return c;
    }
    

    Addendum: While technically correct, note that the editor component's color is typically managed by the corresponding UI delegate while active. An unfortunate choice may result in poor contrast and impaired usability. Thorough testing on target Look & Feels is warranted.

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