user3973309
user3973309

Reputation:

java clear a JPanel with a transparent background

I have been attempting to create a screen saver program. Essentially, there are multiple circles that move around the screen. However, when I make the background transparent I cannot use clearRect() anymore because that will force the background to be white. Is there any way to clear the already drawn circles while keeping the background transparent?

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

Upvotes: 1

Views: 2565

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347332

Don't use alpha based colors with Swing components, instead, simply use setOpaque(false)

Change

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

to

mySS.setOpaque(false)

Swing only knows how to paint opaque or transparent components (via the opaque property)

As a personal preference, you should also be calling super.paintComponent before you do any custom painting, as your paintComponent really should be making assumptions about the state

Upvotes: 2

Related Questions