java使用Turtle绘制一个三角形
时间: 2023-06-11 16:04:12 浏览: 108
python turtle 绘图案例002- 绘制三角形
好的,以下是使用Java Turtle绘制三角形的代码:
```java
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TurtleTriangle extends JPanel {
private ArrayList<Point> points;
private static final int PANEL_WIDTH = 500;
private static final int PANEL_HEIGHT = 500;
public TurtleTriangle() {
points = new ArrayList<>();
initializePoints();
setPreferredSize(new Dimension(PANEL_WIDTH, PANEL_HEIGHT));
}
private void initializePoints() {
int startX = PANEL_WIDTH / 2;
int startY = PANEL_HEIGHT - 100;
int leftX = startX - 100;
int leftY = PANEL_HEIGHT - 300;
int rightX = startX + 100;
int rightY = PANEL_HEIGHT - 300;
points.add(new Point(startX, startY));
points.add(new Point(leftX, leftY));
points.add(new Point(rightX, rightY));
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLACK);
for (int i = 0; i < points.size(); i++) {
int start = i;
int end = (i + 1) % points.size();
int startX = (int) points.get(start).getX();
int startY = (int) points.get(start).getY();
int endX = (int) points.get(end).getX();
int endY = (int) points.get(end).getY();
g.drawLine(startX, startY, endX, endY);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("TurtleTriangle");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new TurtleTriangle());
frame.pack();
frame.setVisible(true);
}
}
```
在这个例子中我们使用了一个 `JPanel`,在这个面板中我们使用了 `TurtleTriangle` 类来绘制三角形。在类的构造函数中,我们初始化了三个点,分别代表三角形三个顶点的坐标。在 `paintComponent()` 方法中,我们将三个点以线的形式连接起来,形成一个三角形。
希望这个代码可以解决你的问题,有问题就在问吧。
阅读全文