Cell Renderer for JTable - coloured rows

后端 未结 4 1913
太阳男子
太阳男子 2021-01-23 09:58

I\'ve been looking around for a solution to this and I can\'t make head nor tail from various places of how to get my table to do coloured rows without asking my own question.

4条回答
  •  鱼传尺愫
    2021-01-23 10:26

    Maybe this works for you:

    class MyCellRenderer extends DefaultTableCellRenderer {
         String separatedVariable;
         public MyCellRenderer(String separatedVariable) {
             this.separatedVariable = separatedVariable;
          }
    
          @Override
          public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {
              Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
              c.setBackground(Color.WHITE);
              c.setForeground(Color.BLACK);
                  JLabel l = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
              if (separatedVariable.equals("YOUR VALUE TO GREEN")) {
                  l.setBackground(Color.GREEN);
    
                  return l;
              } else {
                         if (separatedValue.equals("YOUR VALUE TO YELLOW")) {
                              l.setBackground(Color.YELLOW);
                              return l;
                          } else if (separatedValue.equals("YOUR VALUE TO RED")) {
                              l.setBaground(Color.RED);
                              return l;
                          }
                   }
                  return c;
          }
    }
    

提交回复
热议问题