2013-03-14 20 views
1

我想使用的顏色,在我的GWT客戶端,使用Color類在GWT

我想這種顏色

    public static Color myColor = new Color(152, 207, 204) ; 

,如果我用這個進口

    import java.awt.Color; 

在客戶端它給我的錯誤:

   No source code is available for type java.awt.Color; did you forget to inherit a required module 

怎麼可以我在GWT客戶端使用RGB顏色,不使用CSS。

回答

4

你可以寫一個簡單的RGB到字符串轉換:

public final class Helper { 
    public static String RgbToHex(int r, int g, int b){ 
     StringBuilder sb = new StringBuilder(); 
     sb.append('#') 
     .append(Integer.toHexString(r)) 
     .append(Integer.toHexString(g)) 
     .append(Integer.toHexString(b)); 
     return sb.toString(); 
    } 
} 

並使用它:

nameField.getElement().getStyle().setBackgroundColor(Helper.RgbToHex(50, 100, 150)); 

---更新---

更復雜的方式與控制負值,大於255和0-15值。

public static String RgbToHex(int r, int g, int b){ 
    StringBuilder sb = new StringBuilder(); 
    sb.append('#') 
    .append(intTo2BytesStr(r)) 
    .append(intTo2BytesStr(g)) 
    .append(intTo2BytesStr(b)); 
    return sb.toString(); 
    } 

    private static String intTo2BytesStr(int i) { 
    return pad(Integer.toHexString(intTo2Bytes(i))); 
    } 

    private static int intTo2Bytes(int i){ 
    return (i < 0) ? 0 : (i > 255) ? 255 : i; 
    } 

    private static String pad(String str){ 
    StringBuilder sb = new StringBuilder(str); 
    if (sb.length()<2){ 
     sb.insert(0, '0'); 
    } 
    return sb.toString(); 
    } 
+0

謝謝:),完美工作 – junaidp 2013-03-14 08:34:10

+0

我不認爲這對R/G/B值小於16十進制(10十六進制)的情況很好......例如(5,10,20)將導致包含「#5a14」的字符串...不是你想要的! – 2013-03-18 04:45:25

+0

@安迪金你對。但是這裏還有其他一些問題:1. int的負值。 2.值> 255。 – FFire 2013-03-18 08:27:29

2

您正在使用AWB類Color

GWT != Java . //so gwt compiler wont compile the awt classes 

改爲使用此ThirdParty Color Class

只需將該類複製到您的utility package中,然後在client side上使用它。

+0

謝謝,實際上我使用它在CellTable與擴展行,所以我以前使用這使我的列顏色:td.style()。trustedBackgroundColor(「blue」); ::現在它沒有采取任何東西,除了字符串,任何方式,我可以給這些RGB顏色到我的celltable細胞。 – junaidp 2013-03-14 07:44:58

+0

可能是該方法只需要w3c誹謗的顏色..這裏是standered colrs列表http://www.docsteve.com/DocSteve/TechNotes/color_test.html。 – 2013-03-14 07:51:16

+0

謝謝,這個清單+1,這將是有益的,但理想情況下有一些方法來把我自己的RGB顏色 – junaidp 2013-03-14 07:54:44

0

這是一個被FFire的RgbToHex方法的更正確的版本從答案(該版本將正常工作的R/G/B值小於16):

public static String rgbToHex(final int r, final int g, final int b) { 
    return "#" + (r < 16 ? "0" : "") + Integer.toHexString(r) + (g < 16 ? "0" : "") + 
     Integer.toHexString(g) + (b < 16 ? "0" : "") + Integer.toHexString(b); 
} 

當然,你如果您願意,可以使用StringBuilder