• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to add a BufferedImage to a JPanel  RSS feed

 
Suhel Sayyed
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I need to add a buffered image to JPanel. Can anyone please help me out. I am using the following method for this :-



public void paintComponent(Graphics g) {
// This is TEST Code
PdfDecoder decode_pdf = new PdfDecoder();
PdfDecoder.setFontReplacements(decode_pdf);
BufferedImage img = new BufferedImage(50, 50, BufferedImage.TYPE_INT_ARGB);
try {
decode_pdf.openPdfFile("C:/Excel_Temp/MedicationLogSheet.pdf");
img = decode_pdf.getPageAsImage(1);
decode_pdf.closePdfFile();
} catch(PdfException e){
AppParam.getLog().error("PDFException while adding image in PDF");
}
Graphics2D gph = (Graphics2D) (img.getGraphics());
gph.dispose();
g.drawImage(img, 0, 0, null);
}

This method will be invoked as following :-

Graphics g = null;
pnlMainContent.paintComponent(g);


I am encountering a null pointer exception. Any inputs please?
 
Harsha Smith
Ranch Hand
Posts: 287
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
check at what line of the code, you are getting NPE. An object reference is null at that line and you are trying to invoke a method on it.
 
John Jai
Rancher
Posts: 1776
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From the code posted the below line might throw the exception...

since you send the reference as null

 
Rob Spoor
Sheriff
Posts: 21052
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You shouldn't:
a) call paintComponent directly.
b) do any extensive work (like opening a file) from paintComponent. Painting can occur several times a second, and therefore also the opening. Instead, open the file before you paint, keep a reference to the image, then call repaint(). Let paintComponent draw the stored image.

I'll move this to our GUI forum.
 
Randall Twede
Ranch Hand
Posts: 4683
8
Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sounds very similar to the problem i'm having(see post: problem with JDialog). i knew about not calling paintComponent directly but not about not opening files etc. i'm betting that is the problem.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!