java编写可添加图片的屏保程序
时间: 2024-05-16 17:16:10 浏览: 147
java用applet编写屏保程序
4星 · 用户满意度95%
以下是一个简单的 Java 屏幕保护程序,可以在屏幕上显示一些随机的图片:
```java
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class ScreenSaver extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
private static final int DELAY = 50; // 屏幕刷新时间间隔
private static final int NUM_IMAGES = 10; // 图片数量
private static final int MAX_ROTATION_SPEED = 3; // 图片旋转速度的最大值
private ArrayList<Image> images = new ArrayList<Image>(); // 图片列表
private ArrayList<AffineTransform> transforms = new ArrayList<AffineTransform>(); // 变换矩阵列表
private Random rand = new Random(); // 随机数生成器
private Timer timer; // 定时器
public ScreenSaver() {
// 加载图片
for (int i = 0; i < NUM_IMAGES; i++) {
try {
Image image = ImageIO.read(new File("image" + i + ".jpg"));
images.add(image);
} catch (IOException e) {
e.printStackTrace();
}
}
// 初始化变换矩阵
for (int i = 0; i < NUM_IMAGES; i++) {
AffineTransform transform = new AffineTransform();
transform.translate(rand.nextInt(getWidth()), rand.nextInt(getHeight()));
transform.rotate(rand.nextDouble() * Math.PI * 2);
transforms.add(transform);
}
// 启动定时器
timer = new Timer(DELAY, this);
timer.start();
}
@Override
public void actionPerformed(ActionEvent e) {
// 更新变换矩阵
for (int i = 0; i < NUM_IMAGES; i++) {
AffineTransform transform = transforms.get(i);
double rotationSpeed = rand.nextDouble() * MAX_ROTATION_SPEED;
transform.rotate(rotationSpeed / 180.0 * Math.PI);
transforms.set(i, transform);
}
// 重新绘制屏幕
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// 绘制背景
g2d.setColor(Color.BLACK);
g2d.fillRect(0, 0, getWidth(), getHeight());
// 绘制图片
for (int i = 0; i < NUM_IMAGES; i++) {
Image image = images.get(i);
AffineTransform transform = transforms.get(i);
g2d.drawImage(image, transform, null);
}
g2d.dispose();
}
public static void main(String[] args) {
JFrame frame = new JFrame("Screen Saver");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setUndecorated(true);
ScreenSaver saver = new ScreenSaver();
frame.add(saver);
frame.setVisible(true);
}
}
```
你需要将图片保存在程序所在目录下,文件名为 "image0.jpg" 到 "image9.jpg"。你也可以修改程序中的常量来调整程序的行为。
阅读全文