Search code examples
javapaintcomponent

I can't display image from file (paintComponent)


I have problem with displaying image from file:

public class Drawing extends JPanel
{
    public void paintComponent(Graphics g)
    {
        //g.setColor(Color.ORANGE);
        //g.fillRect(20, 50, 100, 100);
        Image picture = new ImageIcon("test.jpg").getImage();
        g.drawImage(picture, 3, 4, this);
    }
    public static void main(String[] args) 
    {
    Drawing gui1 = new Drawing();
    JFrame frame = new JFrame();
    frame.setSize(300, 300);
    frame.setVisible(true);
    frame.add(gui1);
    frame.repaint();
    }
}

It should be simple. I have file test in folder with class Drawing. I do not know what I'm doing wrong.

paintComponent works, I know that because I displayed a square from this code. I'm using book Head First Java.


Solution

  • Best way to manage Images, is to create a folder in your project:"src/resources", and copy your images there, after you can use this code to load the image:

    InputStream stream = getClass().getClassLoader().getResource("myImage.png");
    ImageIcon icon= new ImageIcon(ImageIO.read(stream));
    

    This should work in your IDE and also when the application is distributed in a jar file ;)