用java编写一个会转动的风扇,风扇有一根柱子,五片扇叶,
时间: 2024-01-24 21:17:11 浏览: 157
以下是一个简单的Java风扇类,其中包括了风扇的转动功能。
```java
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class Fan extends JPanel implements Runnable {
private static final long serialVersionUID = 1L;
private int angle = 0;
private int speed = 5;
private int x = 150;
private int y = 150;
private int radius = 100;
private int bladeCount = 5;
private Color bladeColor = Color.BLUE;
public Fan() {
Thread thread = new Thread(this);
thread.start();
}
@Override
public void run() {
while (true) {
angle += speed;
repaint();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.WHITE);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.BLACK);
g.drawOval(x - radius, y - radius, radius * 2, radius * 2);
for (int i = 0; i < bladeCount; i++) {
int bladeAngle = angle + i * (360 / bladeCount);
int bladeX = (int) (x + radius * Math.cos(Math.toRadians(bladeAngle)));
int bladeY = (int) (y + radius * Math.sin(Math.toRadians(bladeAngle)));
g.setColor(bladeColor);
g.drawLine(x, y, bladeX, bladeY);
}
}
public void setSpeed(int speed) {
this.speed = speed;
}
public void setBladeCount(int bladeCount) {
this.bladeCount = bladeCount;
}
public void setBladeColor(Color bladeColor) {
this.bladeColor = bladeColor;
}
}
```
使用方法:
```java
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
Fan fan = new Fan();
fan.setSpeed(10);
fan.setBladeCount(5);
fan.setBladeColor(Color.RED);
frame.add(fan);
frame.setVisible(true);
}
}
```
这个类继承自 `JPanel`,并且实现了 `Runnable` 接口,其中的 `run()` 方法用来控制风扇的转动。使用 `paintComponent()` 方法来绘制风扇,可以通过 `setSpeed()`、`setBladeCount()` 和 `setBladeColor()` 方法来设置风扇的转速、叶片数和颜色。在 `main()` 方法中创建一个 `Fan` 对象,并设置相关属性,然后将其添加到 `JFrame` 中即可。
阅读全文