2

I have a JPanel, with some components like buttons, labels, table, etc.

What I want to do is to add a functionality (a jButton), that clicking on that button directs me to print the whole panel, along with labels and components. Please help.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
shivshnkr
  • 1,435
  • 1
  • 13
  • 19

1 Answers1

0

Just make a JButton that calls this code:

public void printComponent() {

  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());
      componenet_name.paint(g2);
      return Printable.PAGE_EXISTS;
    }
  });

  if (pj.printDialog() == false) return;

  try {
    pj.print();
  } catch (PrinterException ex) {
    // handle exception
  }
}

(taken from: How can I print a single JPanel's contents?)

S. Esteves
  • 415
  • 4
  • 14
MedMik
  • 144
  • 1
  • 12