Question

This is the code i tried to use to paint an image on screen (location of the image is correct), the code runs but nothing is drawn on the screen. My program's getFile() and paintComponent() method:

BufferedImage image;    
public void getFile() throws IOException{
    image = ImageIO.read(new File("grass.png"));
}
protected void paintComponent(Graphics g) 
{
    super.paintComponent(g);
    g.drawImage(image, 0, 0, null);
}
}
Was it helpful?

Solution

You do realise that you never create an instance of DrawImage nor do you actually add it to anything that could display it

public class DrawImage extends JPanel
{

    BufferedImage image;

    public DrawImage() throws IOException {
        getFile();
    }

    public void getFile() throws IOException
    {
        image = ImageIO.read(new File("grass.png"));
    }

//...

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    DrawImage pane = new DrawImage();
                    JFrame frame = new JFrame();
                    frame.add(pane);
                    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                    frame.setSize(400, 400);
                    frame.setVisible(true);    
                } catch (IOException exp) {
                    exp.printStackTrace();
                }
            }
        });
    }

OTHER TIPS

Instead of JPanel pane = new JPanel(), you should do DrawImage pane = new DrawImage() and before you do frame.add(pane) call pane.getFile().

Since you always need to call getFile() before drawing the DrawImage, why don't you put it into a constructor of the DrawImage class?

First you didn't use your class that draw the image (DrawImage) in this line JPanel pane = new JPanel(); so you must change it to DrawImage pane = new DrawImage(); second issue you didn't invoke getFile() method to initialize image object so either use as I mentioned below or invoke this method as your write in class drawImage constructor.

public class DrawImage extends JPanel{

BufferedImage image;

public Image getFile() 
{
    try {
        image = ImageIO.read(new File("grass.png"));
        return image;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}


protected void paintComponent(Graphics g) 
{
    super.paintComponent(g);
    System.out.println(image);
    g.drawImage(getFile(), 0, 100, null);
}

public static void main(String[] args)
{
    DrawImage pane = new DrawImage();
    JFrame frame = new JFrame();
    frame.add(pane);
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.setSize(400, 400);
    frame.setVisible(true);    
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top