0

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??!

Andy
  • 263
  • 1
  • 11
  • g.drawImage is null which is None in python, how can you expect even in python, that you can call a method on None/null? – quant Jul 17 '14 at 22:56
  • The main problem you have, is that you first have to create something to draw this image to. So have a look at the java "window toolkits" awt, swing or javafx. Create such a java window and then add your Image to it. – quant Jul 17 '14 at 22:59
  • Your main problem is that you're trying to code without first looking at some tutorials. This is well explained and all easily found with just a little effort. – Hovercraft Full Of Eels Jul 17 '14 at 23:06
  • To Quant - The null was a recommendation by Eclipse To Hovercraft - I got the code that's working from a tutorial but this side of things was only vaugely explained – Andy Jul 17 '14 at 23:33

1 Answers1

4

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

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366