22

I have a JPanel with two labels with pictures. I need to print these content of the JPanel. Please help me out. How can I print only this JPanel's contents, as I also have different components on my JFrame but I just need to print this JPanel.

Thanks.

Eddie
  • 53,828
  • 22
  • 125
  • 145
Talha Bin Shakir
  • 2,563
  • 10
  • 38
  • 54

3 Answers3

27

Here is an example to print any Swing component.

public void printComponenet(Component component){
  PrinterJob pj = PrinterJob.getPrinterJob();
  pj.setJobName(" Print Component ");

  pj.setPrintable (new Printable() {    
    public int print(Graphics pg, PageFormat pf, int pageNum){
      if (pageNum > 0){
      return Printable.NO_SUCH_PAGE;
      }

      Graphics2D g2 = (Graphics2D) pg;
      g2.translate(pf.getImageableX(), pf.getImageableY());
      component.paint(g2);
      return Printable.PAGE_EXISTS;
    }
  });
  if (pj.printDialog() == false)
  return;

  try {
        pj.print();
  } catch (PrinterException ex) {
        // handle exception
  }
}
ArchLinuxTux
  • 840
  • 1
  • 11
  • 28
Talha Bin Shakir
  • 2,563
  • 10
  • 38
  • 54
5

A simple way to do it would be implementing the Printable interface (in java.awt.print) and adding the specified print method (it works similar to paint—in here, you could specify what components you would want to draw onto the printed page). And when you want to actually print the contents of the panel, obtain a PrinterJob instance and call its setPrintable method, passing the object that implemented Printable.

That's just a quick overview, though. I'd recommend taking a look at Sun's tutorial on printing for further information.

hbw
  • 15,560
  • 6
  • 51
  • 58
0

just edit and put the name of your frame, panel(jPanel1) and button(print). 'this' refers to the JFrame class(i.e my class extends javax.swing.JFrame ) just put your frame's reference instead of 'this'.

private void PritnActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    Toolkit tkp = jPanel1.getToolkit();
    PrintJob pjp = tkp.getPrintJob(this, null, null);
    Graphics g = pjp.getGraphics();
    jPanel1.print(g);
    g.dispose();
    pjp.end();
}
YasirAzgar
  • 1,385
  • 16
  • 15