简体   繁体   中英

How to make JFrame background image transparent?

Currently, I'm using this code to generate a background image for my JFrame:

    BufferedImage myImg = ImageIO.read(myUrl);
    this.setContentPane(new ImagePanel(myImg));

    //ImagePanel class
    public class ImagePanel extends JComponent {
        private Image image;
        public ImagePanel(Image image) {
            this.image = image;
        }

        @Override
        protected void paintComponent(Graphics g) {
            g.drawImage(image, 0, 0, null);
        }
    }

As a result of this, the image covers up everything that I have in the JFrame. How can I toggle the transparency of the image being drawn so that I can still see my content while having the image set as the background?

protected void paintComponent(Graphics g) {
        g.drawImage(image, 0, 0, null);

Should be:

protected void paintComponent(Graphics g) {
        super.paintComponent(g);  // paint the parent component!
        g.drawImage(image, 0, 0, this);

EG

  1. Answer to Drawing a background image.
  2. Answer to Background image hides all GUI design components.

Why do you keep talking about transparency? You would only care about transparency if you are painting an image "on top" of your components.

If you want a background image on your frame then you add the image to a panel and add the panel to the frame. Then you add other components to the background panel so that those components are displayed on top of the image.

This has nothing to do with transparency.

The background panel is generally a JPanel, not a JComponent since a panel is designed to be used as a container.

See Background Panel for an example.

You can't just change an image to make it transparent. You need to load an image with transparent pixels.

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