How can I print a single JPanel's contents?

前端 未结 3 458
感动是毒
感动是毒 2020-11-29 03:28

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 JPa

3条回答
  •  日久生厌
    2020-11-29 04:26

    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
      }
    }
    

提交回复
热议问题