java 清除具有透明背景的 JPanel

java clear a JPanel with a transparent background

我一直在尝试创建屏幕保护程序。本质上,有多个圆圈在屏幕上移动。但是,当我使背景透明时,我不能再使用 clearRect() 因为这会强制背景为白色。有什么方法可以清除已经绘制的圆圈,同时保持背景透明?

class ScreenSaver extends JPanel implements ActionListener {
static Timer t;
Ball b[];
int size = 5;

ScreenSaver() {
    Random rnd = new Random();
    b = new Ball[size];
    for (int i = 0; i < size; i++) {
        int x = rnd.nextInt(1400)+100;
        int y = rnd.nextInt(700)+100;
        int r = rnd.nextInt(40)+11;
        Color c = new Color(rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
        int dx = rnd.nextInt(20)-10;
        if (dx == 0)
            dx++;
        int dy = rnd.nextInt(20)-10;
        if (dy == 0)
            dy++;

        b[i] = new Ball(x, y, r, c, incR, incG, incB, dx, dy);
    }
}
public void actionPerformed(ActionEvent e) {
    repaint();
}
public void paintComponent(Graphics g) {
    //g.clearRect(0, 0, 1600, 900);

    for (int i = 0; i < size; i++) {
        if (b[i].x + b[i].r+b[i].dx >= 1600)
            b[i].dx *= -1;
        if (b[i].x - b[i].r+b[i].dx <= 0)
            b[i].dx *= -1;
        if (b[i].y + b[i].r+b[i].dy >= 900)
            b[i].dy *= -1;
        if (b[i].y - b[i].r+b[i].dy <= 0)
            b[i].dy *= -1;

        b[i].x += b[i].dx;
        b[i].y += b[i].dy;

        g.fillOval(b[i].x-b[i].r, b[i].y-b[i].r, b[i].r*2, b[i].r*2);
    }        
}
}
class Painter extends JFrame{
Painter() {
    ScreenSaver mySS = new ScreenSaver();
    mySS.setBackground(new Color(0, 0, 0, 0)); //setting the JPanel transparent
    add(mySS);

    ScreenSaver.t = new Timer(100, mySS);
    ScreenSaver.t.start();

    setTitle("My Screen Saver");
    setExtendedState(JFrame.MAXIMIZED_BOTH);
    setLocationRelativeTo(null);
    setUndecorated(true);
    setBackground(new Color(0, 0, 0, 0)); //setting the JFrame transparent
    setVisible(true);
}
}

不要对 Swing 组件使用基于 alpha 的颜色,而是简单地使用 setOpaque(false)

改变

mySS.setBackground(new Color(0, 0, 0, 0));

mySS.setOpaque(false)

Swing 只知道如何绘制不透明或透明组件(通过 opaque 属性)

根据个人喜好,您还应该在进行任何自定义绘画之前调用 super.paintComponent,因为您的 paintComponent 确实应该对状态做出假设