简体   繁体   中英

Making a JFrame containing a JPanel transparent

This is regarding a Java Swing application. I have a JFrame whose contentPane is set to a JLayer . The JLayer has its border set to TitledBorder . This is how the resulting GUI looks like.

https://lh5.googleusercontent.com/-wL6CwKUFUmc/UIaZlc4VHNI/AAAAAAAABNo/4ccgAePrg8Y/s344/dgf.png

I want the JFrame to be completely transparent so that the resulting GUI has a JLayer with a rounded rectangle as the border. Only the rounded rectangle should be visible. The light gray colour surrounding it shouldn't be visible. How can it be done?

This is how the final GUI should look like.

https://lh3.googleusercontent.com/-Gvce0j_frHI/UIaYKgBOc-I/AAAAAAAABNY/jnbl4qLWa1M/s344/border.png

Here is a short program illustrating the above problem:

public class del extends javax.swing.JFrame {

    JPanel loginPanel;

    public del() {
        initComponents();
    }

    public void initComponents() {
        loginPanel = new javax.swing.JPanel();
        loginPanel.setBackground(new java.awt.Color(204, 204, 204));
        loginPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        add(loginPanel);
        setUndecorated(true);
        setMinimumSize(new Dimension(100, 100));
        setLocation(200, 200);
    }

    public static void main(String args[]) throws Exception {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }

            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new del().setVisible(true);
                }
            });
        }
    }
}

And here is the resulting GUI:

在此输入图像描述

Continuing my comment...

Here is an example I made hope it helps:

Basically overrides componentResized(ComponentEvent e) of JFrame changing its shape to RoundRectangle2D . Then a JPanel is added with custom AbstarctBorder to take care of round edges of border.

在此输入图像描述

import java.awt.*;
import static java.awt.GraphicsDevice.WindowTranslucency.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.geom.RoundRectangle2D;
import javax.swing.*;
import javax.swing.border.AbstractBorder;

public class ShapedWindowAndBorderDemo extends JFrame {

    public ShapedWindowAndBorderDemo() {
        super("Shaped Window and Border Demo");

        final JPanel panel = new JPanel() {
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(200, 200);
            }
        };
        // It is best practice to set the window's shape in
        // the componentResized method.  Then, if the window
        // changes size, the shape will be correctly recalculated.
        addComponentListener(new ComponentAdapter() {
            // Give the window an elliptical shape.
            // If the window is resized, the shape is recalculated here.
            @Override
            public void componentResized(ComponentEvent e) {
                setShape(new RoundRectangle2D.Float(panel.getX(), panel.getY(), panel.getWidth(), panel.getHeight(), 10, 10));
            }
        });


        setUndecorated(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //panel.setBorder(new CurvedBorder());//creates a single lined border
        panel.setBorder(new CurvedBorder(2, true));
        panel.add(new JButton("I am a Button"));
        add(panel);

        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }

    public static void main(String[] args) {
        // Determine what the GraphicsDevice can support.
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        GraphicsDevice gd = ge.getDefaultScreenDevice();

        //If shaped windows aren't supported, exit.
        if (!gd.isWindowTranslucencySupported(PERPIXEL_TRANSPARENT)) {
            System.err.println("Shaped windows are not supported");
            System.exit(0);
        }


        // Create the GUI on the event-dispatching thread
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new ShapedWindowAndBorderDemo();
            }
        });
    }
}

class CurvedBorder extends AbstractBorder {

    private Color wallColor = Color.gray;
    private int sinkLevel = 1;
    private boolean indent = false;

    public CurvedBorder(Color wall) {
        this.wallColor = wall;
    }

    public CurvedBorder(int sinkLevel, Color wall, boolean indent) {
        this.wallColor = wall;
        this.sinkLevel = sinkLevel;
    }

    public CurvedBorder(int sinkLevel, boolean indent) {
        this.sinkLevel = sinkLevel;
        this.indent = indent;
    }

    public CurvedBorder() {
    }

    @Override
    public void paintBorder(Component c, Graphics g, int x, int y, int w, int h) {
        super.paintBorder(c, g, x, y, w, h);
        g.setColor(getWallColor());

        for (int i = 0; i < sinkLevel; i++) {
            g.drawRoundRect(x, y, w - 1 - i, h - 1 - i, 10 - i, 10 - i);
            if (indent) {
                g.drawRoundRect(x + i, y + i, w - 1, h - 1, 10 - i, 10 - i);
            }
        }
    }

    @Override
    public boolean isBorderOpaque() {
        return true;
    }

    @Override
    public Insets getBorderInsets(Component c) {
        return new Insets(sinkLevel, sinkLevel, sinkLevel, sinkLevel);
    }

    @Override
    public Insets getBorderInsets(Component c, Insets i) {
        i.left = i.right = i.bottom = i.top = sinkLevel;
        return i;
    }

    public boolean isIndented() {
        return indent;
    }

    public int getSinkLevel() {
        return sinkLevel;
    }

    public Color getWallColor() {
        return wallColor;
    }
}

Reference

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