0

I am currently working on a text-based RPG with a GUI and I can't seem to get the image I want to use to load.

class BackgroundPanel extends Panel
{
    // The Image to store the background image in.
    Image img;
    public BackgroundPanel(String location)
    {
        // Loads the background image and stores in img object.
        img = Toolkit.getDefaultToolkit().createImage(location);
    }

    public void paintComponent(Graphics g)
    {
        // Draws the img to the BackgroundPanel.
        g.drawImage(img, 0, 0, null);
        img.setAccelerationPriority(SCALE_FAST);
    }
}

This is the code I use for the panel itself. I tried putting the image file in the root directory of my project but it doesn't seem to help. I have created a folder within the project which I intend to use for all of my images.

I'm not sure what the issue is here. I know I tried using paint() instead of paintComponent(), but then the buttons and other components won't draw until you mouse over them, for some reason.

Any ideas?

APerson
  • 8,140
  • 8
  • 35
  • 49

1 Answers1

0

I have already posted it at below links in the same context. Please have a look:


It's already described in Oracle Java Tutorial on Loading Images Using getResource

Note: Don't forget to call super.paintComponent() in the overridden paintComponent() method.

Community
  • 1
  • 1
Braj
  • 46,415
  • 5
  • 60
  • 76
  • Hi Braj . currently i am loading the image as `FileSystemResource res = new FileSystemResource(new File("D:/Logo.jpg"));` is it possible to load from my project structure . something like `File(/webappName/images)` ? – Santhosh Sep 23 '14 at 10:11
  • Is it a web project or just a standalone swing project? Are you using it inside the Applet? Have you tried all the links that I shared you from my another posts? – Braj Sep 23 '14 at 10:20
  • It is a spring web application project . i looked at your posts it is more of swing . can you pls help me ? – Santhosh Sep 23 '14 at 10:25
  • In web application, you should use Application Context to get the real path of the resources that reside inside the war. Try [ServletContext#getRealPath()](http://docs.oracle.com/cd/E17802_01/products/products/servlet/2.5/docs/servlet-2_5-mr2/javax/servlet/ServletContext.html#getRealPath%28java.lang.String%29) – Braj Sep 23 '14 at 10:50
  • Can you pls describe it or link an example – Santhosh Sep 23 '14 at 10:52
  • here is an [example](http://stackoverflow.com/questions/8623709/output-an-image-file-from-a-servlet) – Braj Sep 23 '14 at 10:53