2017-08-02 16 views
0

我正在爲Color類中的對象編寫訪問器。我想返回與該對象關聯的紅色,綠色和藍色值的總和。有沒有辦法讓我調用我創建的對象的參數?如何從Java對象中調用RBG參數

這是我到目前爲止已經無濟於事試圖....

// Sample // 



int red = 200; 
int green = 51; 
int blue = 76; 

Color c = new Color(red, green, blue); 
System.out.println(c.red); 
System.out.println(c.green); 
System.out.println(c.blue); 

// The above gives a compile error // 
+0

請出示'Color'源 –

+0

這是顏色C =新的色彩(紅,綠,藍)或本 的System.out.println(c.red);導致問題? – JFPicard

+0

請注意'c.red'不會**指向顏色對象的內部紅色值。它寧可指向表示全紅色*(255,0,0)*的常量「顏色」對象。該變量是** static **,因此它應該由'Color.red'而不是'c.red'引用,因爲它不是'c'對象的成員,而是'Color'類。如果你想訪問c對象的紅色屬性,那麼你應該使用'c.getRed()'。就像一個註釋,'Color'還爲所有類型的顏色定義了其他常量,例如'Color.BLACK'或'Color.LIGHTBLUE'。 – Zabuza

回答

2

找到該信息的最好的地方通常是Java文檔中 - 爲Color類你可以找到它here

要回答你的問題,如果你有一個Color對象,你應該可以調用c.getBlue(),c.getRed()和c.getGreen(),它們應該以整數形式返回。

+0

我可以在不創建新訪問器的情況下獲取值嗎? – samgrey

+0

你是什麼意思?如果您使用的是Java Color類,則訪問器是類的一部分,您只需要有一個Color對象。 – Nkdy

+1

如果這是個問題,你不需要自己創建這樣的方法。這個* getter-methods *是Color類的一部分。 – Zabuza

1

使用getRed(),getGreen(),getBlue()。

import java.awt.*; 

public class colors123 { 
public static void main (String args[]) { 
    int red = 200; 
    int green = 51; 
    int blue = 76; 

    Color c = new Color(red, green, blue); 
    System.out.println(c.getRed()); 
    System.out.println(c.getGreen()); 
    System.out.println(c.getBlue()); 
    System.out.println(c.getRed()+c.getGreen()+c.getBlue()); 

    } 
} 
+0

有沒有辦法做到這一點,沒有每種顏色的新訪問器? – samgrey

+0

你能改述這個問題嗎?上述代碼有什麼問題? Color類沒有直接訪問其內部,它們被標記爲** package visible **。因此他們提供這種**吸氣劑**方法。請注意,「顏色」對象甚至不會按照您的想法記住顏色。它使用字節操作將它們高效地存儲在一個'int'內,如下所示:http://i.imgur.com/xKjN2rc.jpg。您可以自己查看整個源代碼,例如:http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/awt/Color的.java – Zabuza

相關問題