为什么jtable输出不在纸上打印?

时间:2015-06-03 05:33:13

标签: java swing printing jtable

我已经从下面的数据库中填充了jtable。![在此输入图像描述] [1] 现在我正在尝试将此输出发送到打印机。但是当我单击打印按钮时,纸张上的输出不正确。

我使用过这种方法。

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(table), postformat);
                if (pjob.printDialog()) {
                    try {
                        pjob.print();
                    } catch (PrinterException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
    });

2.Printer Class

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

0 个答案:

没有答案