0

我正在尝试创建一个表数组(2 个表)。我的程序在最后一行停止,出现空指针异常。知道为什么吗?

com.lowagie.text.pdf.PdfPTable[] table = new com.lowagie.text.pdf.PdfPTable[1];
// the cell object
com.lowagie.text.pdf.PdfPCell cell;
// header

cell = new PdfPCell(new Phrase(wdComponentAPI.getMessage("Ordernr")));
cell.setColspan(1);
cell.setBackgroundColor(Color.LIGHT_GRAY);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table[0].addCell(cell);
4

3 回答 3

1

您创建了数组,但其中没有任何内容。数组字段“table[0]”包含空值。

像这样添加对象:

tables[0] = new PdfPTable();

或者根据您的确切需要使用与 PdfPTable() 不同的构造函数

这是您更新的代码

com.lowagie.text.pdf.PdfPTable[] table = new com.lowagie.text.pdf.PdfPTable[1];
tables[0] = new PdfPTable();
// the cell object
com.lowagie.text.pdf.PdfPCell cell;
// header

cell = new PdfPCell(new Phrase(wdComponentAPI.getMessage("Ordernr")));
cell.setColspan(1);
cell.setBackgroundColor(Color.LIGHT_GRAY);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table[0].addCell(cell);
于 2014-04-25T07:35:57.083 回答
1

数组不是由创建的对象创建的

PdfPTable [] tables = new PdfPTable[1];
tables[0].doStuff() // null pointer

在数组中创建对象

PdfPTable [] tables = new PdfPTable[1];
tables[0] = new PdfPTable();
tables[0].doStuff() // works good!
于 2014-04-25T07:36:47.070 回答
1

com.lowagie.text.pdf.PdfPTable[] table = new com.lowagie.text.pdf.PdfPTable[1];

你只是创建了一个长度为 1 的数组,此时table[0]仍然null如此。您必须先创建一个对象并将其分配给它,然后才能使用它

table[0] = new PdfPTable(1); // create a PDFTable with one column
于 2014-04-25T07:37:28.583 回答