Java - set opacity in JPanel

前端 未结 6 709
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-09 10:16

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.

6条回答
  •  误落风尘
    2020-12-09 10:28

    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

提交回复
热议问题