有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

swing java清除带有透明背景的JPanel

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

  1. # 1 楼答案

    不要在Swing组件中使用基于alpha的颜色,只需使用setOpaque(false)

    改变

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

    mySS.setOpaque(false)
    

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

    作为个人偏好,你也应该在做任何定制绘画之前打电话给super.paintComponent,因为你的paintComponent真的应该对国家做出假设