tags:

views:

320

answers:

3

Hello, 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 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());
    }
}

What am I doing wrong here? Well I came from PHP and ECMAScripts where I was able to pass my function arguments this way so I really don't understand this error.

+6  A: 

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);
}
T.J. Crowder
+2  A: 

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.

SLaks
+1  A: 

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);
}
Mnementh