Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何使用非静态方法?_Java_Static_Drawstring - Fatal编程技术网

Java 如何使用非静态方法?

Java 如何使用非静态方法?,java,static,drawstring,Java,Static,Drawstring,我已经搜索了一段时间,文档和谷歌都没有返回一个好的答案。我刚开始使用java,请帮我一把。我有个错误 Graphics.drawString('hello',10, 10); 然而,所有的文档都告诉我,我需要使用str,int,int。 我的错误是: Cannot make a static reference to the non-static method drawString(str,int,int) from the type Graphics 那么有人知道如何解决这个问题吗?您需要

我已经搜索了一段时间,文档和谷歌都没有返回一个好的答案。我刚开始使用java,请帮我一把。我有个错误

Graphics.drawString('hello',10, 10);
然而,所有的文档都告诉我,我需要使用str,int,int。 我的错误是:

Cannot make a static reference to the non-static method drawString(str,int,int) from the type Graphics

那么有人知道如何解决这个问题吗?

您需要使用
图形的实例,正如错误消息所说的那样

i、 e

基本上,
static
方法是从类中调用的,而非静态方法必须使用该类的实际对象来调用

但是,您需要从某处获取
图形
实例,因为类本身是
受保护的
而不是
公共的
,并且类本身是
抽象的
。(对于初学者来说,这意味着您需要在某个地方使用该对象,因为您无法直接为自己创建它。)


另外,旁注:单引号用于
char
文字,而双引号用于
String
文字。

drawString()方法不是静态的。这意味着您需要图形(或Graphics2D)对象的实例。通常,当您使用此对象时,它会作为paint()方法的参数传递给您。

在理解GUI应用程序之前,您应该先了解这些基本概念。Oracle上有教程:我强烈建议您阅读一本很好的Java入门教材,熟悉基本概念(即静态和非静态之间的区别)。请发布整个课程的简化示例。Groditz,请务必选择并回答,并在适当的地方给出rep。
Graphics graphics = new Graphics();
graphics.drawString("hello", 10, 10);