java int 不能取消引用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2402008/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
int cannot be dereferenced
提问by Delta
I am beginning in java (I'm learning in microedition) and I got this error: "int cannot be dereferenced" in the following class:
我从 Java 开始(我在微版本中学习),但在以下课程中出现此错误:“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());
}
}
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.
我在这里做错了什么?好吧,我来自 PHP 和 ECMAScripts,在那里我能够以这种方式传递我的函数参数,所以我真的不明白这个错误。
回答by T.J. Crowder
The gin drawStringis the color value you've passed in, not your Graphicsreference. So the error is when you're trying to call a method on an int, which you can't do.
在g中drawString是你已经通过色彩值,而不是你的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);
}
回答by SLaks
You are calling the setColorand fillRectmethods on g, which is a parameter of type int.
Since intis not a reference type, you cannot call methods on it.
您正在调用setColor和fillRect方法g,这是一个类型的参数int。
由于int不是引用类型,因此不能对其调用方法。
You probably want to add a Graphicsparameter to the function.
您可能希望Graphics向该函数添加一个参数。
回答by Mnementh
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:
当 g 在绘制方法中时,方法 drawString 中的类 Graphics(包含名为 setColor、fillRect 和 drawString 的方法)的对象被 g 定义为包含绿色值的整数。特别是在g.setColor(r, g, b);您使用 g 设置颜色的行中,也用作设置颜色的参数。int 没有方法 setColor (这也没有意义),所以你会得到一个错误。您可能还想在此方法中获得一个 Graphics 对象。当您扩展画布时,您可以通过调用 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);
}

