I want to read a jpg image from a file to an Image object and then paint it on my JPanel, but the image doesn't appear.I've tried drawing some other stuff on the panel (like lines etc.) and everything appeared without any problems.

My code:

This class represents my JPanel:

public class Scene extends JPanel {
    private Image backgroundImage=null;

    public Scene(){
        super();
        setDoubleBuffered(true);
        
        try {
            backgroundImage = ImageIO.read(new File("bg.jpg"));
        } catch (IOException ex) {
        }
    }

    @Override
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        g.drawImage(backgroundImage, 0, 0, 400, 600, this);
    }
    
}

This is my JFrame, on which i put my JPanel.

public class Window extends JFrame{
    private Scene scene;
    
    public Window(){
        super();
        setSize(400,600);
        setLocation(300,100);
        setVisible(true);
        setResizable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());
        setResizable(false);


        scene=new Scene();
        add(scene,BorderLayout.CENTER);

        requestFocus();
    }

Any ideas?

Recommended Answers

Try adding the entire path to your image file. It may just be a resource location issue. If that works, you may want to use getResource() for locating the file resources as discussed in this tutorial:

Jump to Post

All 4 Replies

Ive already tried adding the whole path and it didnt make a difference

Ok, change your Window class constructor just a bit to this

public Window(){
        super();
        scene=new Scene();
        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(scene,BorderLayout.CENTER);

        setSize(400,600);
        setLocation(300,100);
        setVisible(true);
        setResizable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        requestFocus();
    }

The main difference is adding your "Scene" panel to the content pane of the JFrame and doing it before the setSize() and setResizable() calls.

It worked! Thanks alot

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.