修改版本1中Fan类,让其继承Pane类,并且把color属性设置为Color类型,默认属性为red。随机产生radius,取值范围为1-5;随机产生颜色,取值范围为red、blue、yellow、green、orange;根据color、radius属性值绘制风扇。运行如下图:
时间: 2024-03-20 21:41:52 浏览: 60
好的,根据您的需求,修改的Fan类如下:
```java
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Arc;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Shape;
import java.util.Random;
public class Fan extends Pane {
private final int SLOW = 1;
private final int MEDIUM = 2;
private final int FAST = 3;
private int speed = SLOW;
private boolean on = false;
private double radius;
private Color color;
public Fan() {
setRadius();
setColor();
}
public void setRadius() {
Random random = new Random();
this.radius = random.nextDouble() * 4 + 1;
}
public void setColor() {
Random random = new Random();
Color[] colors = {Color.RED, Color.BLUE, Color.YELLOW, Color.GREEN, Color.ORANGE};
this.color = colors[random.nextInt(colors.length)];
}
public int getSpeed() {
return speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public boolean isOn() {
return on;
}
public void setOn(boolean on) {
this.on = on;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public void drawFan() {
getChildren().clear();
if (on) {
double centerX = getWidth() / 2.0;
double centerY = getHeight() / 2.0;
Circle circle = new Circle(centerX, centerY, radius * 40, Color.TRANSPARENT);
circle.setStroke(Color.BLACK);
circle.setStrokeWidth(2);
getChildren().add(circle);
for (int i = 0; i < 4; i++) {
Arc arc = new Arc(centerX, centerY, radius * 40, radius * 40, i * 90 + 30, 30);
arc.setFill(color);
arc.setType(Shape.Type.ROUND);
getChildren().add(arc);
}
} else {
Circle circle = new Circle(getWidth() / 2.0, getHeight() / 2.0, radius * 40, Color.TRANSPARENT);
circle.setStroke(Color.BLACK);
circle.setStrokeWidth(2);
getChildren().add(circle);
}
}
}
```
以上代码实现了继承Pane类,重写了drawFan方法来根据属性值绘制风扇,并且添加了随机产生radius和color属性值的方法。您可以在其他类中实例化Fan类并调用其drawFan方法来绘制风扇。
阅读全文