java使用StdDraw创建一个Turtle实现 Turtle Graphics API中setPenColor的功能
时间: 2023-06-08 19:08:41 浏览: 43
你好!关于你的问题,可以使用以下代码实现:
```java
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import javax.swing.JFrame;
public class Turtle {
private static double x;
private static double y;
private static double angle;
private static JFrame frame;
public static void main(String[] args) {
frame = new JFrame();
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
setPenColor(Color.RED);
penDown();
forward(100);
turnLeft(90);
forward(100);
turnLeft(90);
forward(100);
turnLeft(90);
forward(100);
frame.dispose();
}
public static void setPenColor(Color color) {
Graphics2D g = (Graphics2D) frame.getContentPane().getGraphics();
g.setPaint(color);
}
public static void penDown() {
x = 250;
y = 250;
}
public static void forward(double distance) {
double newX = x + distance * Math.cos(angle * Math.PI / 180);
double newY = y - distance * Math.sin(angle * Math.PI / 180);
Graphics2D g = (Graphics2D) frame.getContentPane().getGraphics();
Line2D line = new Line2D.Double(x, y, newX, newY);
g.draw(line);
x = newX;
y = newY;
}
public static void turnLeft(double turnAngle) {
angle += turnAngle;
}
}
```
这是一个简单的 Turtle Graphics API 实现,并且可以使用 setPenColor 方法设置画笔的颜色。具体的实现方式是使用 Graphics2D 类的 setPaint 方法。希望能够帮到你!