int无法解除引用

我是从java开始的(我正在学习microedition)并且我得到了这个错误:“int不能被解除引用”在下面的类中:

class DCanvas extends Canvas{ public DCanvas(){ } public void drawString(String str, int x, int y, int r, int g, int b){ g.setColor(r, g, b); //The error is here g.drawString(str, x, y, 0); //and here } public void paint(Graphics g){ g.setColor(100, 100, 220); g.fillRect(0, 0, getWidth(), getHeight()); } } 

我在这做错了什么? 好吧,我来自PHP和ECMAScripts,我能够以这种方式传递我的函数参数,所以我真的不明白这个错误。

drawStringg是您传入的颜色值,而不是Graphics引用。 所以错误是当你试图在int上调用一个方法时,你不能这样做。

 // Passing an integer 'g' into the function here | // V public void drawString(String str, int x, int y, int r, int g, int b){ // | This 'g' is the integer you passed in // V g.setColor(r, g, b); g.drawString(str, x, y, 0); } 

您正在调用g上的setColorfillRect方法,这是int类型的参数。
由于int不是引用类型,因此无法在其上调用方法。

您可能想要为该函数添加Graphics参数。

虽然g在paint-method中,但是方法drawString中的Graphics类(包含名为setColor,fillRect和drawString的方法)的对象被定义为包含绿色值的Integer。 特别是在行g.setColor(r, g, b); 你用g来设置它的颜色,也作为设置颜色的参数。 int没有方法setColor(也没有意义),所以你得到一个错误。 您可能也想在此方法中获取Graphics对象。 在扩展canvas时,可以通过调用getGraphics()来获取图形对象,因此您的示例可能如下所示:

 public void drawString(String str, int x, int y, int r, int g, int b){ getGraphics().setColor(r, g, b); getGraphics().drawString(str, x, y, 0); }