如何使一个透明的JFrame,但保持一切一样吗?(How to make a transparent

2019-07-20 02:20发布

我想使JFrame透明,但在它上面的图像是不透明的。 这是我现在有:

有谁知道一种方法,使仅有JFrame透明?

这里是我的代码:

import javax.swing.*;
import java.awt.*;
import com.sun.awt.AWTUtilities;
import static java.awt.GraphicsDevice.WindowTranslucency.*;

public class SplashDemo extends JFrame
{
    public SplashDemo()
    {
        setUndecorated(true);
        setSize(200, 200);

        add(new JLabel(new ImageIcon("puppy2.png"))); 
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setVisible(true);

        setOpacity(0.85f);      
    }

     public static void main(String[] args) 
     {
        new SplashDemo();
     }
}

Answer 1:

基本上,你需要做一个透明窗口,半透明的内容窗格。 这添加到内容窗格将意味着什么,将继续无需额外alphering要呈现...

public class TranscluentWindow {

    public static void main(String[] args) {
        new TranscluentWindow();
    }

    public TranscluentWindow() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (Exception ex) {
                    }

                    JWindow frame = new JWindow();
                    frame.setAlwaysOnTop(true);
                    frame.addMouseListener(new MouseAdapter() {
                        @Override
                        public void mouseClicked(MouseEvent e) {
                            if (e.getClickCount() == 2) {
                                SwingUtilities.getWindowAncestor(e.getComponent()).dispose();
                            }
                        }
                    });
                    frame.setBackground(new Color(0,0,0,0));
                    frame.setContentPane(new TranslucentPane());
                    frame.add(new JLabel(new ImageIcon(ImageIO.read(getClass().getResource("/Puppy.png")))));
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }

            }
        });
    }

    public class TranslucentPane extends JPanel {

        public TranslucentPane() {
            setOpaque(false);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g); 

            Graphics2D g2d = (Graphics2D) g.create();
            g2d.setComposite(AlphaComposite.SrcOver.derive(0.85f));
            g2d.setColor(getBackground());
            g2d.fillRect(0, 0, getWidth(), getHeight());

        }

    }

}


文章来源: How to make a transparent JFrame but keep everything else the same?