简体   繁体   中英

super.paint() not visible over image

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);
   }
}

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.

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, ie over the other stuff. It's like all kind of paintings. What you draw later will be over the previously draw.

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")));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM