1
 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());
    }
}

这是我放置一些褪色效果的面板。不透明度使用摇摆的 Timer 类更新。问题是当所有插入值都设置为 0 计时器工作但我只看到最终结果没有任何褪色效果。但是,即使其中一个插图设置为某个非零值,我也可以看到褪色效果。怎么了,求救?

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

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

或者

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

1 回答 1

3

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();
}
于 2012-08-20T21:12:17.660 回答