I am beginning in java (I\'m learning in microedition) and I got this error: \"int cannot be dereferenced\" in the following class:
class DCanvas extends Can
You are calling the setColor
and fillRect
methods on g
, which is a parameter of type int
.
Since int
is not a reference type, you cannot call methods on it.
You probably want to add a Graphics
parameter to the function.
The g
in drawString
is the color value you've passed in, not your Graphics
reference. So the error is when you're trying to call a method on an int
, which you can't do.
// 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);
}
While g is in the paint-method an object of the class Graphics (that contains methods named setColor, fillRect and also drawString) in the method drawString is g defined as an Integer that conatins the value for the color green. Especially in the line g.setColor(r, g, b);
you use g to set a color on it and also as the argument for setting the color. int has no method setColor (that also doesn't make sense), so you get an error. You probably want to get an Graphics-object also in this method. As you extend canvas, you can get a graphics-object by calling getGraphics(), so your example could look like this:
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);
}