2010-01-05 3 views
1

3 열에 null이 아닌지 여부에 따라 표 행에 색상을 지정하고 싶습니다. 내가 쓴 을 Heres 코드 : 나는 테이블의 모든 행을 실행에만 1 행 3 열에서 null 이외의 값이있는 경우에도 색받을 때 (괄호를 무시가)Java 테이블 행 착색하기

public Component prepareRenderer(TableCellRenderer renderer, int row, int column) { 

     JComponent c =(JComponent) super.prepareRenderer(renderer, row, column); 
     c.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY, 1)); 
     if (column == 2){ 

       String value = (String) getValueAt(row, column); 
       System.out.println(value); 

       if (! value.equals(null)){ 

        c.setForeground(Color.RED); 
       } 
      } 

문제는 . 어디서 잘못 가고 있습니까?

+0

슈퍼는 무엇이며 무엇이 반환됩니까? – Bozho

+0

메소드 prepareRenderer가 JTable – Goutham

+0

을 확장하여 System.out.println (value)을 삽입하고 메소드가 호출 될 때 실제 값을 확인하는 클래스 내에 있습니다. – Bozho

답변

2

JTable의 기본 렌더러는 여러 셀에서 공유되는 전체 테이블의 단일 인스턴스입니다. 전경을 설정하면 모든 전경에 대해 설정됩니다. 값이 널이 아닌 경우 기본 색상으로 다시 설정해야합니다. 또한 왜 == null 대신 .equals (null)을 사용하고 있습니까?

+0

감사합니다. . equals에 관해서는, 나의 자바는 여전히 약간 불안정합니다. – Goutham

2

효율성을 위해 super.prepareRenderer()에 의해 반환 된 구성 요소는 테이블의 여러 셀에서 사용됩니다. 그래서, 당신은 else 경로를 처리해야합니다. 나는 다음을 시도합니다 :

if (column == 2){ 
    String value = (String) getValueAt(row, column); 
    System.out.println(value); 

    if (value == null){ 
    // I suppose this one may not be needed since the value is null 
    // and nothing should appear in the table. 
    c.setForeground(Color.Black); 
    } else { 
    c.setForeground(Color.RED); 
    } 
} else { 
    // This is definitely needed 
    c.setForeground(Color.Black); 
} 
0

내가 그 값이 다음

value.equals (NULL)이

NullPointerException이 던져 때문에 결코 null의 희망!