public class FadingLayer extends JPanel {

    public FadingLayer(JPanel panel) {
        // when set to "insets 0 0 0 0", shows the FadingPanel without fading.
        setLayout(new MigLayout("insets 1 0 0 0"));
        add(panel,"dock center");
        setOpaque(false);
    }

    @Override
    public void paintComponent(Graphics arg0) {
        Graphics2D graphics = (Graphics2D) arg0;
        AlphaComposite alpha = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, opacity);
        graphics.setComposite(alpha);
        graphics.setColor(getBackground());
        graphics.fillRect(0, 0, getWidth(), getHeight());
    }
}


这是我要在面板上放置一些淡入淡出效果的面板。使用Swing的Timer类更新不透明度。问题是,当所有插入值都设置为0时,定时器工作了,但是我看到的最终结果没有任何褪色效果。但是,即使将其中一个插图设置为某个非零值,我也会看到渐变效果。怎么了,请帮忙?

编辑:
当面板(添加到FadingPanel中)获取完整区域时,就会发生这种情况。那就是FadingPanel设置为->

 setLayout(new BorderLayout());
 add(panel,BorderLayout.CENTER);


要么

setLayout(new MigLayout("insets 0 0 0 0"));
add(panel,"dock center");

最佳答案

SagarDabas的回答是正确的,我只想发表一些评论

public void paintComponent(Graphics arg0) {
    Graphics2D graphics = (Graphics2D) arg0;
    AlphaComposite alpha = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, opacity);
    graphics.setComposite(alpha);
    graphics.setColor(getBackground());
    graphics.fillRect(0, 0, getWidth(), getHeight());
}


在处理图形上下文时,您必须非常小心。上面的代码将影响所有在其之后绘制的组件(保留使用alpha合成)

更好的方法是在开始之前复制图形。

public void paintComponent(Graphics arg0) {
    Graphics2D graphics = (Graphics2D) arg0.create();
    // paint as normal
    graphics.dispose();
}

07-26 02:55