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
}
}
Best Answer
You've declared
g2d
as aGraphics
object, andGraphics
doesn't have thedrawImage(BufferedImage, BufferedImageOp, int, int)
method. Fix: replace the linewith
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 castedg
to aGraphics2D
doesn't make a difference unless you actually store it in a variable of typeGraphics2D
.