Search code examples
javajpanelopacity

Java - set opacity in JPanel


Let's say I want to make the opacity of a JPanel %20 viewable? I don't mean setOpaque (draw or not draw) or setVisible (show or hide)... I mean make it see-through JPanel.. you know?

Is this possible?


Solution

  • You need to set the "alpha" value for your Color object:

    panel.setBackground( new Color(r, g, b, a) );
    

    However, this will still not work properly as Swing doesn't paint transparent background properly so you need to do custom painting. The basic logic is:

    JPanel panel = new JPanel()
    {
        protected void paintComponent(Graphics g)
        {
            g.setColor( getBackground() );
            g.fillRect(0, 0, getWidth(), getHeight());
            super.paintComponent(g);
        }
    };
    panel.setOpaque(false); // background of parent will be painted first
    panel.setBackground( new Color(255, 0, 0, 20) );
    frame.add(panel);
    

    Check out Backgrounds With Transparency for more information on the actual painting problem and why the above code solves the problem. The link also contains a custom reusable class that does the above painting for you.