用java代码for循环画三角形,并且保存到自定义的文件夹里
时间: 2023-05-21 22:03:02 浏览: 90
好的,以下是用 Java 代码 for 循环画三角形并保存到自定义文件夹的示例代码:
```java
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class TriangleDrawer {
public static void main(String[] args) {
int width = 300;
int height = 300;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
g.setColor(Color.BLACK);
int x1 = 50, y1 = 50;
int x2 = 150, y2 = 250;
int x3 = 250, y3 = 50;
g.drawLine(x1, y1, x2, y2);
g.drawLine(x2, y2, x3, y3);
g.drawLine(x3, y3, x1, y1);
g.dispose();
try {
File outputfile = new File("custom_folder/triangle.png");
outputfile.getParentFile().mkdirs();
ImageIO.write(image, "png", outputfile);
System.out.println("Triangle saved to " + outputfile.getAbsolutePath());
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
```
这段代码会在自定义的文件夹 "custom_folder" 中生成一个名为 "triangle.png" 的文件,里面是一个画好的三角形。
阅读全文