java清除具有透明背景的JPanel

时间:2016-05-03 19:26:46

标签: java swing graphics jpanel transparent

我一直在尝试创建一个屏幕保护程序。基本上,有多个圆圈在屏幕上移动。但是,当我使背景透明时,我不能再使用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);
}
}

1 个答案:

答案 0 :(得分:2)

不要将基于alpha的颜色与Swing组件一起使用,而只需使用setOpaque(false)

更改

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

mySS.setOpaque(false)

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

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