Java:无法从类型组件对非静态方法createImage(int,int)进行静态引用
可能重复:Java:无法从类型组件对非静态方法createImage(int,int)进行静态引用,java,Java,可能重复: 我试图平铺背景,但现在我卡住了。我已经阅读了createImage()的文档,但由于某些原因,有些东西是静态的,我不知道如何或为什么 以下是我的代码: Paint paint; if (paint == null) { try { // Create TexturePaint instance the first time Component c; Image image = c.g
我试图平铺背景,但现在我卡住了。我已经阅读了
createImage()
的文档,但由于某些原因,有些东西是静态的,我不知道如何或为什么
以下是我的代码:
Paint paint;
if (paint == null) {
try {
// Create TexturePaint instance the first time
Component c;
Image image = c.getToolkit().getImage("Background.png");
int height = image.getHeight(null);
int width = image.getWidth(null);
BufferedImage bi = (BufferedImage) Component.createImage(width, height);
Graphics2D biG2d = (Graphics2D) bi.getGraphics();
biG2d.drawImage(image, 0, 0, Color.black, null);
paint = new TexturePaint(bi, new Rectangle(0, 0, width, height));
} catch (Exception ex) {
ex.printStackTrace();
}
}
我在网上找不到一个答案,所以我不知道出了什么问题(
非常感谢您的支持。createImage似乎不是一个静态方法,因此您无法使用类名直接访问该方法
createImage
是实例方法,所以您需要实例化Component
并从该实例调用createImage
例如:
Component comp = new Component(..);
comp.createImage(...);
这一行:
BufferedImage bi = (BufferedImage) Component.createImage(width, height);
不正确。您正在对不存在的组件
类进行静态调用。鉴于您在代码的更高层声明了一个组件
实例,但尚未初始化,因此不确定您试图完成什么。如果您这样做:
BufferedImage bi = (BufferedImage) c.createImage(width, height);
您将不再收到编译器警告,但运行代码将为您带来一个NPE。您可能希望更好地定义您要完成的任务。尝试此操作,它将在您的
组件的实例上调用该方法:
BufferedImage bi = (BufferedImage) c.createImage(width, height);
可能不是这条线
BufferedImage bi = (BufferedImage) Component.createImage(width, height);
您应该使用组件对象c来代替:
BufferedImage bi = (BufferedImage) c.createImage(width, height);
然而,我看不出c在代码中除了当前的null之外还有什么其他特性。但这可能是一个单独的问题,您可以自己解决。大概您要将这个TexturePaint
对象设置为您要创建的Graphics2D
对象的Paint
属性从组件中获取。您需要使用相同的组件创建缓冲图像。我只需要找到一种不同的方法来平铺背景。这种方法是不可能的。但是如果我删除它,我会出现以下错误:方法createImage(int,int)类型DisplayMap的未定义。我不确定您的外部类是什么,因为您没有在代码示例中发布它。但是您必须对组件的正确初始化子类调用createImage
。在您的代码中,c
变量初始化在哪里?