2010-01-05 36 views
1

我想爲表格行着色,具體取決於第3列是否存在非空值。 繼承人,我寫的代碼:(忽略括號)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); 
       } 
      } 

問題是,當我執行這一切的表中的行獲得彩色即使只有1排在第3列一個非空值。 我哪裏錯了?

+0

什麼是超級,它返回什麼? – Bozho 2010-01-05 04:48:50

+0

prepareRenderer方法在擴展JTable的類中 – Goutham 2010-01-05 04:55:16

+0

放置一個System.out.println(value)並在調用該方法時檢查實際值。 – Bozho 2010-01-05 05:01:03

回答

2

JTable的默認渲染器是跨多個單元共享的整個表的單個實例。一旦你設置了前景,它將被設置爲它的所有用法。當值不爲空時,應將其設置回默認顏色。另外,爲什麼你使用.equals(null)而不是== null?

+0

感謝這有助於。至於.equals,我的java仍然有點不穩定。 – Goutham 2010-01-05 05:33:08

2

出於效率的原因,super.prepareRenderer()返回的組件由表中的多個單元格使用。所以,你需要處理其他途徑。我會嘗試以下方法:

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

我希望值是永遠不能爲null,因爲那時

value.equals(空)

會拋出一個NullPointerException!