直接上效果图:
Java代码:
import com.sun.awt.AWTUtilities;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
//这2句是核心
//frame.setBackground(new Color(0,0,0,0));
//pane.setBackground(new Color(0,0,0,0));
//这句写上后没有效果,不知道为什么,jdk1.8
//AWTUtilities.setWindowOpaque(frame, false);
public class t4 {
public static void main(String[] args) {
new t4();
}
public t4(){
start();
}
public static void start() {
final JFrame frame = new JFrame();
frame.setAlwaysOnTop(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setUndecorated(true);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
//这句写上后没有效果,不知道为什么,jdk1.8
//AWTUtilities.setWindowOpaque(frame, false);
//设置透明背景1,重要
frame.setBackground(new Color(0,0,0,0));
final JPanel pane = new JPanel() {
private int[] snowX = null;
private int[] snowY = null;
private int[] angles = null;
private int count = 50;
@Override
public void paint(Graphics g) {
super.paint(g);
Rectangle bounds = frame.getBounds();
if (snowX == null) {
snowX = new int[count];
for (int i = 0; i < snowX.length; i++) {
snowX[i] = getRandomInt(bounds.width);
}
snowY = new int[count];
for (int i = 0; i < snowY.length; i++) {
snowY[i] = getRandomInt(bounds.height);
}
angles = new int[count];
for (int i = 0; i < snowY.length; i++) {
angles[i] = getRandomInt(360);
}
}
Graphics2D g2d = (Graphics2D) g;
InputStream imgIS = this.getClass().getResourceAsStream("snow.png");
Image image = null;
try {
image = ImageIO.read(imgIS);
} catch (IOException e) {
e.printStackTrace();
}
for (int i = 0; i < count; i++) {
//snowX[i] += getRandomInt(5) - 3;
snowY[i] += 5;
angles[i] += i / 5;
snowY[i] = snowY[i] > bounds.height ? 0 : snowY[i];
angles[i] = angles[i] > 360 ? 0 : angles[i];
int x = snowX[i];
int y = snowY[i];
int angle = angles[i];
g2d.translate(x, y);
double angleValue = Math.toRadians(angle);
g2d.rotate(angleValue);
g2d.drawImage(image, 0, 0, null);
g2d.rotate(-angleValue);
g2d.translate(-x, -y);
}
}
};
//设置透明背景2,重要
pane.setBackground(new Color(0,0,0,0));
//这里不设置了
//frame.setContentPane(pane);
frame.setVisible(true);
Thread thread = new Thread() {
@Override
public void run() {
while (true) {
try {
//这里设置一次
frame.setContentPane(pane);
Thread.sleep(10);
//然后移除
frame.remove(pane);
} catch (Exception ex) {
ex.printStackTrace();
}
//然后重画
pane.repaint();
}
}
};
thread.start();
}
public static int getRandomInt(int width) {
int i = 0;
double d = Math.random() * width;
i = (int)d;
return i;
}
}
需要的雪花图片(应该是没有背景的png才对):
说明:
直接复制代码就可以用了,本人是jdk1.8的环境,没有问题。