简体   繁体   中英

Make transparent JFrame with visible borders

I'm trying to create a transparent JFrame , ie a window where the interior is completely transparent while the border, which is the top bar with the close button, minimize etc visible. I tried creating a new Jpanel and then using panel.setOpaque(false); , but it did not help.

I'm extremely new to swing and Java GUI and would love to get some help.

What you want to do is possible, but not in the way you're imagining it...

If you want your standard operating system's window decorations (ie window border, close, maximize, minimize buttons), it's impossible. Transparency cannot be applied to 'decorated' frames.

However, this can be done by using Java's default window decorations. Try out the code below:

public static void main(String[] args) {
    JPanel panel = new JPanel() {
        @Override
        protected void paintComponent(Graphics g) {
            g.setColor(Color.RED);
            g.drawRect(32,32,32,32);
        }
    };

    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame f = new JFrame();
    f.add(panel);
    f.setSize(256,256);

    // The following two statements cause the window-transparency:
    f.setUndecorated(true);
    f.setBackground(new Color(0,255,0,0));

    f.setVisible(true);
}

I personally don't find the Java window decorations very nice looking... Apart from that, OS-specific features (such as Window's Snap feature by 'half-maximizing' a window by moving it to the side of the screen) don't work... To me this is a deal-breaker, but depending on your needs, it could be an acceptable solution. :)

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