利用多线程编程实现一个正在旋转的地球_Java 多线程编程
时间: 2024-01-25 17:03:56 浏览: 38
下面是一个利用Java多线程编程实现正在旋转的地球的示例代码:
```java
import javax.swing.*;
import java.awt.*;
public class RotatingEarth extends JPanel implements Runnable {
private Image earthImage;
private double angle = 0;
private Thread animationThread;
public RotatingEarth() {
earthImage = new ImageIcon("earth.png").getImage();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
int cx = getWidth() / 2;
int cy = getHeight() / 2;
g2d.rotate(angle, cx, cy);
g2d.drawImage(earthImage, cx - 100, cy - 100, 200, 200, this);
g2d.dispose();
}
@Override
public void run() {
while (true) {
angle += 0.01;
repaint();
try {
Thread.sleep(10);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
public void startAnimation() {
if (animationThread == null) {
animationThread = new Thread(this);
animationThread.start();
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Rotating Earth");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
RotatingEarth panel = new RotatingEarth();
panel.setPreferredSize(new Dimension(400, 400));
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
panel.startAnimation();
}
}
```
这个示例代码中,我们定义了一个`RotatingEarth`类,它继承自`JPanel`,同时实现了`Runnable`接口。在`RotatingEarth`类的构造函数中,我们加载了地球图片。在`paintComponent`方法中,我们将画布的坐标系旋转一个角度,然后绘制地球图片。在`run`方法中,我们不断地更新旋转角度并重新绘制地球图片。最后,在`main`方法中,我们创建了一个`JFrame`窗口,并将`RotatingEarth`面板添加到窗口中,启动动画线程。
注意,这个示例代码中的地球图片需要放到与Java源代码文件相同的目录下,并且命名为`earth.png`。你可以根据自己的需要替换这个图片。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)