Java JTable change cell color

后端 未结 7 1538
说谎
说谎 2020-11-30 14:14

I would like to make an editable table and then check the data to make sure its valid. Im not sure how to change the color of just one cell. I would like to get a cell, for

7条回答
  •  孤独总比滥情好
    2020-11-30 14:23

    I believe the correct way to do colouring in a table is via a ColorHighlighter. The table renderers have problems to render different colours in the same column.

    Here is an example of how to use highlighters. In this case it is for highlighting a cell that is not editable.

    public class IsCellEditablePredicate implements HighlightPredicate {
    
       private JXTable table;
    
       public IsCellEditablePredicate (final JXTable table) {
           this.table = table;
       }
    
       @Override
       public boolean isHighlighted(Component component, ComponentAdapter componentAdapter) {
    
            return !table.isCellEditable(componentAdapter.row,
              componentAdapter.column);
       }
    }
    

    and then in your code for setuping the table you add the highlighter and its colour parameters:

     ColorHighlighter grayHighlighter = new ColorHighlighter(new IsCellEditablePredicate(table));
    
        grayHighlighter.setBackground(Color.LIGHT_GRAY);
        grayHighlighter.setForeground(table.getForeground());
        grayHighlighter.setSelectedBackground(table.getSelectionBackground().darker());
        grayHighlighter.setSelectedForeground(table.getSelectionForeground().darker());
    
        table.setHighlighters(grayHighlighter);
    

提交回复
热议问题