java BufferedImage生成表格
时间: 2024-06-13 11:06:43 浏览: 158
可以使用Java的BufferedImage类来生成表格。以下是一个简单的示例代码:
```java
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class TableGenerator {
public static void main(String[] args) {
int rows = 5;
int cols = 3;
int cellWidth = 100;
int cellHeight = 50;
int tableWidth = cols * cellWidth;
int tableHeight = rows * cellHeight;
BufferedImage tableImage = new BufferedImage(tableWidth, tableHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = tableImage.createGraphics();
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, tableWidth, tableHeight);
g2d.setColor(Color.BLACK);
g2d.setFont(new Font("Arial", Font.BOLD, 12));
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
int x = j * cellWidth;
int y = i * cellHeight;
g2d.drawRect(x, y, cellWidth, cellHeight);
g2d.drawString("Cell " + i + "," + j, x + 5, y + 15);
}
}
g2d.dispose();
try {
ImageIO.write(tableImage, "png", new File("table.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这个示例代码生成了一个5行3列的表格,并将其保存为PNG格式的图片。你可以根据需要修改行数、列数、单元格大小、字体等参数来生成不同的表格。
阅读全文