int cannot be dereferenced

后端 未结 3 852
谎友^
谎友^ 2020-11-30 15:19

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         


        
相关标签:
3条回答
  • 2020-11-30 15:33

    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.

    0 讨论(0)
  • 2020-11-30 15:39

    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);
    }
    
    0 讨论(0)
  • 2020-11-30 15:42

    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);
    }
    
    0 讨论(0)
提交回复
热议问题