当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Array of PdfPTables[] nullpointer exception when filling

问题描述:

I'm trying to create an Array of tables (2 tables).

My program stops on the last line with a nullpointer exception. Any idea why?

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);

网友答案:

Arrays dont come created with objects created

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

create the objects inside the array

PdfPTable [] tables = new PdfPTable[1];
tables[0] = new PdfPTable();
tables[0].doStuff() // works good!
网友答案:

You created and array, but there is nothing in it. Array field "table[0]" contains null.

Add there object like this:

tables[0] = new PdfPTable();

Or use a different contructor than PdfPTable(), according to what you exactly need

Here is your code updated

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);
网友答案:

With

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

You just create an array of the length 1, table[0] is still null at this point. You have to create an object and assign it to it before you can use it

table[0] = new PdfPTable(1); // create a PDFTable with one column
分享给朋友:
您可能感兴趣的文章:
随机阅读: