1

I'm having problems with putting a stable image background. I successfully create/draw an image background but when I consecutively run it many times, the image is not showing. The background image seems to be not stable. When I drag the frame to a side of my laptop screen, the image is being erased. How do I create/draw a stable background image that doesn't flicker or erased when dragged?

This code below is what I used for my background image:

public void paint( Graphics g ) {
        super.paint(g);
        g.drawImage(img, -30, 0, null);     //draw image to background
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
ThisGuy
  • 833
  • 1
  • 9
  • 19
  • 1
    I hope you're not serious, for better help sooner post an [SSCCE](http://sscce.org/), short, runnable, compilable, use paintComponent to JPanel, don't to use NullLayout, for e´why reasons there are negative coordinates ---> `g.drawImage(img, -30, 0, null);` – mKorbel Sep 03 '13 at 08:00
  • Duplicate: http://stackoverflow.com/questions/523767/how-to-set-background-image-in-java – rebeliagamer Sep 03 '13 at 09:41
  • oh, thanks. @mKorbel I'll try using JPanel. – ThisGuy Sep 03 '13 at 14:11
  • @rebeliagamer didn't see that, I'll delete this immediately. – ThisGuy Sep 03 '13 at 14:12

1 Answers1

0

Use the JLabel.setIcon(Icon icon) method.

The benefit of this is you don't need to overwrite any method to put a background.

Indeed you can also use JLabel in alternative to JPanel, if you want a container that has an image background. Below can explain this trick in code:

public class JPanelWithBackground extends JLabel {

    public JPanelWithBackground() {
       add(new JButton("I can attached to JLabel? Isn't cool? "));
       setBackgroundImage("path_to_image.png");
    }

    public void setBackgroundImage(String imagePath) {
       setIcon(new ImageIcon(imagePath));
    }
}
richersoon
  • 4,682
  • 13
  • 44
  • 74