问题
The variables value1 to value4 are needed to display in the PDF through the iText PDF generator. When I use the value, it shows "Cannot make a static reference to the non-static field value1". How could I fix that? Here is the code:
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
public class GenerateSummonPDF
{
private String value1;
private String value2;
private String value3;
private String value4; //this variables with constant updated string data
public String getValue1()
{
return this.value1;
}
public void userdata(String p1, String p2, String p3, String p4)
{
this.value1 = p1;
this.value2 = p2;
this.value3 = p3;
this.value4 = p4;
}
public static void main(String[] args)
{
Document document = new Document();
try
{
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:\\Users\\User\\workspace\\enforement system\\Summon PDF list\\Serial No.pdf"));
document.open();
document.add(new Paragraph(getValue1()); //i need to print all the data here from the userdata
document.close();
writer.close();
} catch (DocumentException e)
{
e.printStackTrace();
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
回答1:
You need an instance of GenerateSummonPDF
to call non-static methods:
public static void main(String[] args)
{
GenerateSummonPDF generateSummonPDF = new GenerateSummonPDF(); //create an instance
generateSummonPDF.userdata("TestString1", "TestString2", "TestString3", "TestString4"); //some content
Document document = new Document();
try
{
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:\\Users\\User\\workspace\\enforement system\\Summon PDF list\\Serial No.pdf"));
document.open();
document.add(new Paragraph(generateSummonPDF.getValue1()); //get value1
document.close();
writer.close();
} catch (DocumentException e)
{
e.printStackTrace();
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
回答2:
You are calling the values from the static methods, so that you are getting this error, Just create a function and place your code there like this..
public static void main(String[] args)
{
createPdf();
}
createPdf(){
Document document = new Document();
try
{
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:\\Users\\User\\workspace\\enforement system\\Summon PDF list\\Serial No.pdf"));
document.open();
document.add(new Paragraph(getValue1()); //i need to print all the data here from the userdata
document.close();
writer.close();
} catch (DocumentException e)
{
e.printStackTrace();
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
来源:https://stackoverflow.com/questions/32316788/generating-pdf-with-get-set-variables