Int cannot be dereferenced

I start in java (I study in microdesign) 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 managed to pass arguments to this function, so I really don't understand this error.

+6
java java-me
source share
3 answers

g in drawString is the color value you passed in, not the Graphics link. So the error is that you are trying to call a method on an int that you cannot 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); } 
+8
source share

You call the setColor and fillRect on g , which is an int parameter.
Since int not a reference type, you cannot call methods on it.

You probably want to add the Graphics parameter to the function.

+2
source share

While g is in the paint method, an object of the Graphics class (which contains methods named setColor, fillRect, and also drawString) in the drawString method is g, defined as an integer that encodes the value for green. Especially in the line g.setColor(r, g, b); you use g to set the color on it, and also as an argument to set the color. int doesn't have a setColor method (which also doesn't make sense), so you get an error. You probably also want to get a Graphics object in this method. When you expand the canvas, you can get the graphic by calling getGraphics (), so your example might 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); } 
+1
source share

All Articles