2011-10-12 61 views
1

在我的應用程序中,我正在讀取.xml文件並將數據寫入JTable中。除了表格的數據之外,.xml文件還包含一個定義每行背景顏色的屬性。我對細胞渲染的方法看起來是這樣的:在Java中投射錯誤

 

public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, 
     boolean hasFocus, int row, int col) { 
    JComponent comp = new JLabel(); 

    if (null != value) { 
     //reading the data and writing it in the comp 
    } 

    GenericTableModel model = (GenericTableModel) table.getModel(); 
    GenericObject go = model.getRowObject(row); 

    Color test = new Color(255, 255, 255); 
    if (go.getValueByName("COLOR") == null){ 

    }else{ 
     test =(Color) go.getValueByName("COLOR"); 
    } 

    comp.setBackground(test); 

    return comp; 
} 

.xml文件在程序中被初始化。我的問題是,我不知道如何定義文件中的顏色,以便變量測試可以將其保存爲一種顏色。我試着把它寫成「Color.white」,「white」,甚至是「255,255,255」,但是當我試着將它保存在變量中時,我得到了一個轉換錯誤。

任何想法如何定義文件中的顏色?

+0

我想你想投行對象爲Color對象.. – Rob

+0

沒有...我將正確的對象......這是我在列,並從中獲得唯一的顏色屬性...然後我嘗試投它..這不工作 – schmimona

+0

如果測試是一個字符串,我會寫測試= go.getValueByName(「COLOR」)。toString();它會工作...但是我不能從一個字符串設置組件的背景,我可以嗎? – schmimona

回答

1

我認爲GenericObject#getValueByName()返回一個字符串,對吧?在這種情況下,您需要將字符串轉換爲可用於創建Color實例的內容。假設字符串是「R,G,B」,然後分裂的逗號的串,每個組件轉換爲整數,並創建一個顏色:

public static Color fromString(String rgb, Color deflt) { 
    String[] comp = rgb.split(","); 
    if (comp.length != 3) 
     return deflt; 
    int rc[] = new int[3]; 
    for (int i = 0; i < 3; ++i) { 
     rc[i] = Integer.parseInt(comp[i].trim()); 
     if (rc[i] < 0 || rc[i] > 255) 
      return deflt; 
    } 
    Color c = new Color(rc[0], rc[1], rc[2]); 
    return c; 
} 

另一種方法是定義與彩色色域與Color(Color.BLACK,Color.RED等)中預定義的靜態字段匹配的名稱,並使用反射來獲取正確的字段,但我將其作爲練習。

0

作爲對42個答案的追蹤,它確實取決於應該如何將顏色存儲在XML中。也可以將顏色值保存爲單個字符串(無逗號),表示顏色的十進制或十六進制值。 (十六進制對於顏色更易於人類閱讀,例如對於黃色而言「FFFF00」而不是「16776960」)

例如,爲十進制(和沒有錯誤檢查,根據記錄,我喜歡的默認值等中使用的42)

public static Color readColor(String decimalString) { 
    return new Color(Integer.parseInt(decimalString)); 
} 

public String writeColor(Color color) { 
    return Integer.toString(color.getRGB()); 
} 

例如十六進制(你需要avoidOverflows處理與alpha值的顏色像F)

public static Color readColor(String hexString) { 
    long avoidOverflows = Long.parseLong(hexString, 16); 
    return new Color((int)long); 
} 

public String writeColor(Color color) { 
    return Integer.toHexString(color.getRGB(), 16); 
} 

我還看過一個「#」開頭的十六進制值,以使它們更象HTML。所以,這實際上取決於您的XML規範。