gpt4 book ai didi

java 清除具有透明背景的 JPanel

转载 作者:行者123 更新时间:2023-11-30 02:56:51 25 4
gpt4 key购买 nike

我一直在尝试创建一个屏幕保护程序。本质上,有多个圆圈在屏幕上移动。但是,当我使背景透明时,我不能再使用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 确实应该对状态做出假设

关于java 清除具有透明背景的 JPanel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37012751/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com