0

I'm building a JFrame with an image as a background. I'm overriding the paint() method to draw that image in the JFrame, but when I start the application in Eclipse, none of the JComponents I added are visible. Here's my SSCCE:

public class foo extends JFrame{

   Image i = ImageIO.read(new URL("http://pittsburgh.about.com/library/graphics/regatta_balloons-640.jpg"));

   foo(){
       setSize(100, 100);
       add(new JButton("Foo"));
       setVisible(true);
   }

   @Override public void paint(Graphics g){
        super.paint(g);
        g.drawImage(i, 0, 0, null);
   }
}
celloplayer
  • 31
  • 1
  • 8

3 Answers3

1

Don't override the paint() method of JFrame!!! That is NOT how custom painting is done.

If you are trying to add a background image to your frame then check out Background Panel for a couple of approaches.

camickr
  • 321,443
  • 19
  • 166
  • 288
0

Statements are executed in the order specified by you. If you place g.drawImage after super.paint(g); it will draw the image after the other stuff is draw, i.e. over the other stuff. It's like all kind of paintings. What you draw later will be over the previously draw.

Holger
  • 285,553
  • 42
  • 434
  • 765
  • The problem with placing super.paint(g) after is that I see a gray background instead of the image I want drawn. – celloplayer Sep 23 '13 at 17:35
  • Did you check whether your image really has been loaded correctly? Putting an http url into a `File` looks very strange to be. Though it might work by accident. – Holger Sep 23 '13 at 17:43
  • I clicked copy image location to get the image url, but that wa only for the purposes of the SSCCE. In my real program, it's in a local folder, and I wasn't sure how to post an SSCCE with an image without an http url. – celloplayer Sep 23 '13 at 17:47
  • Then the only thing is that you should have replaced `File` with `URL`. – Holger Sep 23 '13 at 17:52
  • OK...can't believe I didn't think of that. Corrected. – celloplayer Sep 23 '13 at 17:57
  • By the way when I test your code (with `URL`) it does what I expected. It paints the image over the button so the button can't be seen unless I force it by hoovering/clicking. – Holger Sep 23 '13 at 18:06
0

Here is a good tutorial on how to set the background of a JFrame.

JLabel background=new JLabel(new ImageIcon("C:\\Users\\Computer\\Downloads\\colorful design.png"));
add(background);
background.setLayout(new FlowLayout());

OR

setLayout(new BorderLayout());
setContentPane(new JLabel(new ImageIcon("C:\\Users\\Computer\\Downloads\\colorful design.png")));
maryokhin
  • 1,058
  • 13
  • 20