如何在JFrame上正确显示PNG

时间:2014-01-26 14:47:33

标签: java swing png transparency

如何在JFrame上显示带有透明parst的png 我目前有这个代码,一切都很好,但它显示透明部分灰色!

private static void createAndShowSplashScreen() throws Exception {
    Image image = ImageIO.read(TCPServer.class
            .getResource("images/splash.png"));
    BufferedImage img = (BufferedImage) image;

    frame = new JFrame("Splash");
    frame.setUndecorated(true);
    frame.add(new JLabel(new ImageIcon(image)) {
        {
            setOpaque(false);
        }
    });
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setPreferredSize(new Dimension(img.getWidth(), img.getHeight()));
    frame.setBounds((int) (java.awt.Toolkit.getDefaultToolkit()
            .getScreenSize().getWidth() / 2 - img.getWidth() / 2),
            (int) (java.awt.Toolkit.getDefaultToolkit().getScreenSize()
                    .getHeight() / 2 - img.getHeight() / 2),
            img.getWidth(), img.getHeight());
    frame.setOpacity(0f);
    frame.setMinimumSize(frame.getPreferredSize());
    frame.setVisible(true);
}

THX的帮助! 真诚的罗伯托!

编辑: IMG

问题已解决:

Image image = ImageIO.read(TCPServer.class
            .getResource("images/splash.png"));
    BufferedImage img = (BufferedImage) image;

    frame = new JFrame("Splash");
    frame.setUndecorated(true);
    frame.add(new JLabel(new ImageIcon(image)) {
        {
            setOpaque(false);
        }
    });
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setPreferredSize(new Dimension(img.getWidth(), img.getHeight()));
    frame.setBounds((int) (java.awt.Toolkit.getDefaultToolkit()
            .getScreenSize().getWidth() / 2 - img.getWidth() / 2),
            (int) (java.awt.Toolkit.getDefaultToolkit().getScreenSize()
                    .getHeight() / 2 - img.getHeight() / 2),
            img.getWidth(), img.getHeight());
    RoundRectangle2D r = new RoundRectangle2D.Double(0, 0, img.getWidth(), img.getHeight(), 25, 25);
    frame.setShape(r);
    frame.setOpacity(0f);
    frame.setMinimumSize(frame.getPreferredSize());
    frame.setVisible(true);

1 个答案:

答案 0 :(得分:3)

我不知道这是否适合您的具体情况但是如何更改JFrame的形状以匹配图像? setShape(Shape shape)允许您使用geom包中的任何形状。我看到这是一个闪屏并且可能是未修饰的,所以设置形状应该可以解决问题。