用Java,使用多线程思想,让一张地球的图片旋转实现地球的自转
时间: 2024-02-21 17:00:17 浏览: 17
好的,这是一个经典的多线程问题。你可以按照以下步骤实现:
1. 创建一个 JFrame 窗口并在其中添加一个 JLabel 组件来显示地球的图片。
2. 创建一个继承 Thread 类的 EarthRotationThread 线程类,用于控制地球图片的旋转。
3. 在 EarthRotationThread 类中,使用一个 while 循环不断更新地球图片的旋转角度,并通过 JLabel 的 setIcon() 方法更新图片显示。
4. 在 JFrame 窗口中启动 EarthRotationThread 线程,即可实现地球的自转效果。
以下是示例代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
public class EarthRotationDemo extends JFrame {
private JLabel earthLabel;
public EarthRotationDemo() {
super("Earth Rotation Demo");
// 创建 JLabel 并将地球图片添加到其中
earthLabel = new JLabel(new ImageIcon("earth.png"));
earthLabel.setHorizontalAlignment(JLabel.CENTER);
earthLabel.setVerticalAlignment(JLabel.CENTER);
// 将 JLabel 添加到窗口中
getContentPane().add(earthLabel);
// 设置窗口大小和关闭操作
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 启动 EarthRotationThread 线程
new EarthRotationThread().start();
}
// EarthRotationThread 线程类
private class EarthRotationThread extends Thread {
private double angle = 0; // 地球旋转角度
public void run() {
while (true) {
// 更新地球旋转角度
angle += 0.1;
if (angle >= 360) {
angle -= 360;
}
// 旋转地球图片并更新 JLabel 显示
ImageIcon icon = (ImageIcon) earthLabel.getIcon();
Image image = icon.getImage();
BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = bufferedImage.createGraphics();
g2d.rotate(Math.toRadians(angle), image.getWidth(null) / 2, image.getHeight(null) / 2);
g2d.drawImage(image, 0, 0, null);
g2d.dispose();
earthLabel.setIcon(new ImageIcon(bufferedImage));
// 等待一段时间再继续旋转
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
new EarthRotationDemo().setVisible(true);
}
}
```
你可以将上面代码中的 "earth.png" 替换为你自己的地球图片。运行程序后,就可以看到地球自转的效果了。