Creating Transparent JPanel in Swing

It is a quite common question, "how to create transparent panels in swing" and if you think that the solution is critical and involves a lot of hacks, you are wrong. Yes, because creating transparent panels in swing is as easy and you are already might be familiar with it. The transparency can be set using the setBackground() method. Yes, you might have missed the java.awt.Color class' constructor Color(int r,int g,int b,int a); the last parameter here, does it all. The alpha value ranges between 0 and 255 where 0 is full transparent and 255 is fully opaque. An intermediate value, would be semi transparent. In this post, i'll give you an example on how to do this, the program is simple.


import javax.swing.*;
import java.awt.*;
class TransparentPanel extends JFrame
{
JPanel p1,p2;

    public TransparentPanel()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        // Set title and default close operation
        setTitle("Transparent Panel");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
       
        // Set a background for JFrame
        setContentPane(new JLabel(new ImageIcon("E:\\Wallpapers\\frombeyond.jpg")));
       
        // Set some layout, say FlowLayout
        setLayout(new FlowLayout());
       
       
        // Create a JPanel
        p1=new JPanel();
       
        // Set the background, black with 125 as alpha value
        // This is less transparent
        p1.setBackground(new Color(0,0,0,125));
       
        // Create another JPanel
        p2=new JPanel();
       
        // This is more transparent than the previous
        // one
        p2.setBackground(new Color(0,0,0,65));
       
        // Set some size to the panels
        p1.setPreferredSize(new Dimension(250,150));
        p2.setPreferredSize(new Dimension(250,150));
       
        // Add the panels to the JFrame
        add(p1);
        add(p2);
       
        // Set the size of the JFrame and
        // make it visible
        setSize(600,400);
        setVisible(true);
    }
   
   
    public static void main(String args[])
    {
        // Run in the EDT
        SwingUtilities.invokeLater(new Runnable(){
            public void run()
            {
                new TransparentPanel();
            }
        });
    }
}

Output

Two JPanels with semi transparency on black color

You might also be interested in Creating an image with rounded corners, Changing the look and feel at runtime, create a transparent jframe in swing and more ways to set background image in jframe

No comments: