帮我写一个绘制表格图片,能控制每列的单元格宽度且成向单元格填入数据的java代码
时间: 2024-03-05 22:47:35 浏览: 14
好的,以下是一个简单的Java代码示例,可以绘制表格图片并控制每列的单元格宽度,在单元格中填入数据:
```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 TableImageGenerator {
private int width;
private int height;
private int numCols;
private int numRows;
private int[] colWidths;
private String[][] data;
private BufferedImage image;
private Graphics2D g2d;
private Font font = new Font("Arial", Font.PLAIN, 12);
private Color bgColor = Color.WHITE;
private Color fgColor = Color.BLACK;
public TableImageGenerator(int width, int height, int numCols, int numRows, int[] colWidths, String[][] data) {
this.width = width;
this.height = height;
this.numCols = numCols;
this.numRows = numRows;
this.colWidths = colWidths;
this.data = data;
// create a new image buffer
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
g2d = image.createGraphics();
// set background color
g2d.setColor(bgColor);
g2d.fillRect(0, 0, width, height);
// set font
g2d.setFont(font);
// set foreground color
g2d.setColor(fgColor);
}
public void drawTable() {
int x = 0;
int y = 0;
// draw table header
for (int i = 0; i < numCols; i++) {
g2d.drawString(data[0][i], x, y + font.getSize());
x += colWidths[i];
}
// draw horizontal line
y += 2 * font.getSize();
g2d.drawLine(0, y, width, y);
// draw table data
for (int i = 1; i < numRows; i++) {
x = 0;
y += font.getSize();
for (int j = 0; j < numCols; j++) {
g2d.drawString(data[i][j], x, y + font.getSize());
x += colWidths[j];
}
}
}
public void saveImage(String filename) throws IOException {
ImageIO.write(image, "png", new File(filename));
}
public static void main(String[] args) throws IOException {
int width = 400;
int height = 300;
int numCols = 3;
int numRows = 4;
int[] colWidths = {100, 150, 150};
String[][] data = {
{"Name", "Age", "Gender"},
{"John", "25", "Male"},
{"Mary", "30", "Female"},
{"Bob", "35", "Male"}
};
TableImageGenerator generator = new TableImageGenerator(width, height, numCols, numRows, colWidths, data);
generator.drawTable();
generator.saveImage("table.png");
}
}
```
这段代码会生成一个包含表格数据的PNG格式图片文件。你可以根据自己的需求修改代码中的参数来生成不同的表格图片。