tags:

views:

1163

answers:

3

Okay, now I've been using drawImage in java for a while, and this has never happened before. Why can't it find "drawImage(java.awt.image.BufferedImage,<nulltype>,int,int)" in my code?

import java.awt.*;
import javax.swing.*;
import javax.swing.JPanel;
import java.awt.event.*;
import java.awt.image.*;     
import java.io.*;
import java.util.Arrays;
import javax.imageio.ImageIO;

public class imgtest extends JFrame{
    BufferedImage img;
    Graphics g2d;
    /**
     * Creates a new instance of imgtest.
     */
    public imgtest() {
        File file = new File("test.png");
     img = ImageIO.read(file);
    }

    /**
     * @param args the command line arguments
     */
    public void paint(Graphics g)
    {
        g2d = (Graphics2D)g;
        g2d.drawImage(img, null, 0, 0);
    }

    public static void main(String[] args) {
        imgtest i = new imgtest();
        i.setSize(640,480);
        i.setVisible(true);
        i.repaint();
        // TODO code application logic here
    }
}

+4  A: 

You've declared g2d as a Graphics object, and Graphics doesn't have the drawImage(BufferedImage, BufferedImageOp, int, int) method. Fix: replace the line

Graphics g2d;

with

Graphics2D g2d;

When Java is looking for attributes of an object that's stored in a variable like this, it always uses the declared type of the variable, namely Graphics. The fact that you casted g to a Graphics2D doesn't make a difference unless you actually store it in a variable of type Graphics2D.

David Zaslavsky
A: 

You have declared g2d as Graphics and not a Grahphcs2d object

Consider either changing the method call from

 g2d.drawImage(img, null, 0, 0);

to

 (Graphics2d) g2d.drawImage(img, null, 0, 0);

or change your definition of Graphics as in David's post

hhafez
+1  A: 

Along with what other have said about needing to decalre it is a Graphics2D, take it out of the instance variables and make it a local variable. There is no point in having an instance variable that is used in only one method and always has the value overwitten each time that method is called. Instance variables are used to persist state between method calls... you are not doing that here.

public void paint(Graphics g)
{
    final Graphics2D g2d;

    g2d = (Graphics2D)g;
    g2d.drawImage(img, null, 0, 0);
}
TofuBeer
he could be doing more than what is shown in the code snippet ;)
hhafez
In my experience, more often than not that isn't the case unfortunately.
TofuBeer