How to make JFrame background and JPanel transparent with only image showing

一世执手 提交于 2019-12-01 17:25:46

You need to set the ImagePanel to setOpaque(false)

 public ImagePanel() {
        setOpaque(false);

Also you were getting the exception because you need to setUndecorate(true) before you pack();

 JFrame frame = new JFrame();
 frame.add(new ImagePanel());
 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 frame.setUndecorated(true);
 frame.pack(); 
 frame.setBackground(new Color(0, 0, 0, 0)); 
 frame.setVisible(true);

Those are the only two things I changed and it works. Also I got rid of the setSize()

Also use frame.setLocationRelativeTo(null); after pack() to center the frame.


Here's is an example (just for future readers, since I think this may be a popular question)

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.*;

public class CircleSplashScreen {

    public CircleSplashScreen() {
        JFrame frame = new JFrame();
        frame.getContentPane().add(new ImagePanel());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setUndecorated(true);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setBackground(new Color(0, 0, 0, 0));
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new CircleSplashScreen();
            }
        });
    }

    @SuppressWarnings("serial")
    public class ImagePanel extends JPanel {

        BufferedImage img;

        public ImagePanel() {
            setOpaque(false);
            setLayout(new GridBagLayout());
            try {
                img = ImageIO.read(new URL("http://www.iconsdb.com/icons/preview/royal-blue/stackoverflow-4-xxl.png"));
            } catch (IOException ex) {
                Logger.getLogger(CircleSplashScreen.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(500, 500);
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!