2015-06-08 3 views
3

Я стараюсь сделать приложение для качания здесь. Теперь моя цель - распечатать квитанцию. Я установил все детали на JPanel. Я пытаюсь напечатать JPanel в java, но он печатает пустой документ.Как распечатать jpanel в java?

В JPanel Я хочу напечатать это: I want to print only white panel код:

1.ActionListener 

btnPrint.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent arg0) { 
      PrinterJob pjob = PrinterJob.getPrinterJob(); 
      PageFormat preformat = pjob.defaultPage(); 
      preformat.setOrientation(PageFormat.LANDSCAPE); 
      PageFormat postformat = pjob.pageDialog(preformat); 
      //If user does not hit cancel then print. 
      if (preformat != postformat) { 
       //Set print component 
       pjob.setPrintable(new Printer(printPanel), postformat); 
       if (pjob.printDialog()) { 
        try { 
         pjob.print(); 
        } catch (PrinterException e) { 
         // TODO Auto-generated catch block 
         e.printStackTrace(); 
        } 
       } 
      } 
     } 
    }); 

2.Printer Класс:

import java.awt.Component; 
import java.awt.Dimension; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 
import java.awt.print.PageFormat; 
import java.awt.print.Printable; 
import java.awt.print.PrinterException; 

public class Printer implements Printable { 
    final Component comp; 

public Printer(Component comp){ 
    this.comp = comp; 
} 

@Override 
public int print(Graphics g, PageFormat format, int page_index) 
     throws PrinterException { 
    if (page_index > 0) { 
     return Printable.NO_SUCH_PAGE; 
    } 

    // get the bounds of the component 
    Dimension dim = comp.getSize(); 
    double cHeight = dim.getHeight(); 
    double cWidth = dim.getWidth(); 

    // get the bounds of the printable area 
    double pHeight = format.getImageableHeight(); 
    double pWidth = format.getImageableWidth(); 

    double pXStart = format.getImageableX(); 
    double pYStart = format.getImageableY(); 

    double xRatio = pWidth/cWidth; 
    double yRatio = pHeight/cHeight; 


    Graphics2D g2 = (Graphics2D) g; 
    g2.translate(pXStart, pYStart); 
    g2.scale(xRatio, yRatio); 
    comp.printAll(g2); 

    return Printable.PAGE_EXISTS; 
} 



} 
+0

Вы сравниваете ссылки с этой строкой ', если' { – user489041

+0

@ user489041 В самом деле, даже если '(preformat.equals (postformat)) {'может не работать, поскольку' PageFormat.hashCode() 'не переопределяется. Более того, этот оператор следует просто удалить, поскольку отмена диалогового окна страницы означает, что пользователь удовлетворен текущими настройками, и появится диалоговое окно печати. –

+0

Все еще не работает. После удаления if (preformat! = Postformat). –

ответ

0

Простой способ печати компонентов Swing: (! = Предварительно отформатированные postformat)!

/** 
* Create a BufferedImage for Swing components. The entire component will be 
* captured to an image. 
* 
* @param component Swing component to create image from 
* @return image the image for the given region 
*/ 
public static BufferedImage createImage(JComponent component) 
{ 
    Dimension d = component.getSize(); 

    if (d.width == 0 || d.height == 0) 
    { 
     d = component.getPreferredSize(); 
     component.setSize(d); 
    } 

    Rectangle region = new Rectangle(0, 0, d.width, d.height); 
    return ScreenImage.createImage(component, region); 
} 

/** 
* Create a BufferedImage for Swing components. All or part of the component 
* can be captured to an image. 
* 
* @param component Swing component to create image from 
* @param region The region of the component to be captured to an image 
* @return image the image for the given region 
*/ 
public static BufferedImage createImage(JComponent component, Rectangle region) 
{ 
    // Make sure the component has a size and has been layed out. 
    // (necessary check for components not added to a realized frame) 

    if (!component.isDisplayable()) 
    { 
     Dimension d = component.getSize(); 

     if (d.width == 0 || d.height == 0) 
     { 
      d = component.getPreferredSize(); 
      component.setSize(d); 
     } 

     layoutComponent(component); 
    } 

    BufferedImage image = new BufferedImage(region.width, region.height, BufferedImage.TYPE_INT_RGB); 
    Graphics2D g2d = image.createGraphics(); 

    // Paint a background for non-opaque components, 
    // otherwise the background will be black 

    if (!component.isOpaque()) 
    { 
     g2d.setColor(component.getBackground()); 
     g2d.fillRect(region.x, region.y, region.width, region.height); 
    } 

    g2d.translate(-region.x, -region.y); 
    component.paint(g2d); 
    g2d.dispose(); 
    return image; 
} 

public int print(Graphics g, PageFormat pf, int i) throws PrinterException  { 

    /* 
    * User (0,0) is typically outside the imageable area, so we must 
    * translate by the X and Y values in the PageFormat to avoid clipping 
    */ 
    Graphics2D g2d = (Graphics2D) g; 
    g2d.translate(pf.getImageableX(), pf.getImageableY()); 

    //get the image to print 
    BufferedImage theImage = createImage(/*your JPanel*/); 


    double pageWidth = pf.getImageableWidth(); 
    double pageHeight = pf.getImageableHeight(); 
    double imageWidth = theImage.getWidth(); 
    double imageHeight = theImage.getHeight(); 
    double scaleX = pageWidth/imageWidth; 
    double scaleY = pageHeight/imageHeight; 
    double scaleFactor = Math.min(scaleX, scaleY); 
    g2d.scale(scaleFactor, scaleFactor); 
    g.drawImage(theImage, 0, 0, Color.WHITE, null); 

    /* tell the caller that this page is part of the printed document */ 
    return PAGE_EXISTS; 
} 
+0

Но как интегрировать этот код в мой код, как вы можете видеть, это статические методы. :( –

+0

Они должны быть статическими, но они не должны быть. Просто добавьте их в свой класс. – user489041

+0

Что такое метод 'layoutComponent' – ryvantage

0
  • Выключите двойной буферизации непосредственно перед Component.printAll(Graphics g) заявление (хотя помните настройки, чтобы восстановить свое состояние сразу после).

  • Кроме того, я бы использовал один и тот же коэффициент масштабирования для обоих измерений для соответствия формату.

    double xyRatio = Math.min(pWidth/cWidth, pHeight/cHeight); 
    
  • Добавьте регистрацию или System.out.println(String) заявления сужать вниз ваш вопрос!

Смежные вопросы