简体   繁体   中英

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?

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

您还应该查看Backgrounds With Transparency来了解使用它时可能遇到的任何绘画问题。

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:

样品

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 );

替代文字

AWTUtilities.setWindowOpacity(aWindow, aFloat);

其中aWindow是Swing组件,而aFloat是不透明度。

It doesn't work so well on windows 7.

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

the alpha channel just lightens the color.

when an element is updated on a color with an alpha channel, the computer gets confused and resets the background of the updated element without an alpha. I'm going to try

AWTUtilities.setWindowOpacity(aWindow, aFloat);

next.

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.

If you have a custom panel and want the whole thing to be semi-transparent, I advise you to do override its method paintComponent like this :

@Override
    protected void paintComponent(Graphics graphics) {
        super.paintComponent(graphics);
        Graphics2D g2d = (Graphics2D) graphics;
        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
    }

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