Search code examples
javapythonimagedrawingimageobserver

Java - Drawing Images Basically


I've come from Python to Java and am a bit confused. My main question is how to draw an image. I've looked on the oracle site but even when copy - pasting their code it didn't work. Here is what I had (excluding imports):

public class ImageTesting{

public void main(String[] args){
BufferedImage img = null;
try {
    img = ImageIO.read(new File("/Volumes/Data/Users/me/Desktop/Button Img.png"));
    Graphics g = null;
    g.drawImage(img, 100, 100, this);
} catch (IOException e) {
    System.out.println("Image Loading Failed");
}}}

The line I'm having problems is the g.drawImage(img, 100, 100, this); and complains about not having an image observer. It confuses me that that same line works in another code I have but works :/ What am I missing??!


Solution

  • You need something to display your image on.

    The simplest method would be to use a JLabel, see How to use labels for mor examples

    You need a window to display the label, see How to create GUIs with Swing for details

    If, for some reason, you absolutely must paint the image manually, you will need to extend from something that is paintable, like JPanel and override its paintComponent method.

    See How to perform custom painting for more details