Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - set opacity in JPanel

Tags:

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?

like image 567
test Avatar asked Aug 25 '10 01:08

test


People also ask

How do I change the opacity of a JPanel?

You can simply create your jPanel using drag and drop, as you always do and then for changing the panel's color and making it transparent or semi-transparent you can use this code: panel. setBackground(new Color(0.0f, 0.0f, 0.0f, 0.5f));

How do you set transparency in Java?

You set a transparency by creating an AlphaComposite object and then passing the AlphaComposite object to the setComposite method of the Graphics2D object. You create an AlphaComposite by calling AlphaComposite. getInstance with a mixing rule designator and a transparency (or "alpha") value.

How do you make a transparent panel in Java?

JPanel when transparent PNG image is loaded, and set JPanel. setOpaque(false); it will use the image transparent method, else it will show not transparent picture.

What is setOpaque in Java?

The setOpaque() method of a AtomicReference class is used to set the value of this AtomicReference object with memory effects as specified by VarHandle. setOpaque(java.


2 Answers

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

You should also look at Backgrounds With Transparency to understand any painting problems you might have when you use this.

like image 66
camickr Avatar answered Sep 24 '22 03:09

camickr


Use the alpha attribute for the color.

For instance:

panel.setBackground(new Color(0,0,0,64));

Will create a black color, with 64 of alpha ( transparency )

Resulting in this:

sample

Here's the code

package test;

import javax.swing.*;
import java.awt.Color;
import java.awt.BorderLayout;

public class See {
    public static void main( String [] args ){
        JFrame frame = new JFrame();
        frame.setBackground( Color.orange );


        frame.add( new JPanel(){{
                        add( new JLabel("Center"));
                        setBackground(new Color(0,0,0,64));
                    }} , BorderLayout.CENTER );
        frame.add( new JLabel("North"), BorderLayout.NORTH);
        frame.add( new JLabel("South"), BorderLayout.SOUTH);

        frame.pack();
        frame.setVisible( true );
    }
}

With out it it looks like this:

setBackground( new Color( 0,0,0 )  ); // or setBackground( Color.black );

alt text

like image 26
OscarRyz Avatar answered Sep 24 '22 03:09

OscarRyz