views:

66

answers:

5

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?

A: 
AWTUtilities.setWindowOpacity(aWindow, aFloat);

Where aWindow is the Swing component, and aFloat is the opacity.

Mike
Sorry, I don't follow. I don't want a window opacity but JPanel opacity. :D
Dan
A: 

How about override the paintComponent method of the JPanel(in order to do this you have to sub class the JPanel itself and implement your own paintComponent method) inside the paintComponent you can retrieve a buffered image of the component, from there you can manipulate the alpha of the buffered image and paint it back to the JPanel. I have red this long time ago. Still looking for the code.

djakapm
+6  A: 
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.

camickr
the "a" is the alpha setting which is an opacity.
jowierun
Correct, you can also read the API for the Color class to get a complete description of the parameters for the method.
camickr
Thank you. I want to say I am sorry. I should have been more clear.
Dan
+5  A: 

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

OscarRyz
Very nice - worked well!!!
Dan
I'm glad, did you test this in Windows?
OscarRyz
+1  A: 

You might find something appealing in the article How to Create Translucent and Shaped Windows.

trashgod