Why does the alpha in this timer draw on top of itself in this Java Swing Panel?

前端 未结 1 1367
轻奢々
轻奢々 2021-01-15 18:52
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.event.ActionEv         


        
相关标签:
1条回答
  • 2021-01-15 19:30
    this.setBackground(new Color(255, 212, 100, opacity));
    

    Swing does not support transparent backgrounds.

    Swing expects a component to be either:

    1. opaque - which implies the component will repaint the entire background with an opaque color first before doing custom painting, or
    2. fully transparent - in which case Swing will first paint the background of the first opaque parent component before doing custom painting.

    The setOpaque(...) method is used to control the opaque property of a component.

    In either case this makes sure any painting artifacts are removed and custom painting can be done properly.

    If you want to use tranparency, then you need to do custom painting yourself to make sure the background is cleared.

    The custom painting for the panel would be:

    JPanel panel = new JPanel()
    {
        protected void paintComponent(Graphics g)
        {
            g.setColor( getBackground() );
            g.fillRect(0, 0, getWidth(), getHeight());
            super.paintComponent(g);
        }
    };
    panel.setOpaque(false); // background of parent will be painted first
    

    Similar code would be required for every component that uses transparency.

    Or, you can check out Background With Transparency for custom class that can be used on any component that will do the above work for you.

    0 讨论(0)
提交回复
热议问题