开发者

Printing multiple JPanels in a single PrinterJob

So far here is what i have:

//tab is a JTabbedPane

    for(int i = 0; i < tab.getTabCount(); i ++){
        if(tab.getComponent(i) instanceof DuctReport)
            PrintUtilities.printComponent(tab.getComponent(i), DuctReport.PRINT_SIZE);
        else if(tab.getComponent(i) instanceof Vandy)
            PrintUtilities.printComponent(tab.getComponent(i), Vandy.PRINT_SIZE);
        else
            PrintUtilities.printComponent(tab.getComponent(i), .8);
    }

//here is the code for PrintUtilities:

    public class PrintUtilities implements Printable{

    private Component componentToBePrinted;
    private double scale;

    public static void printComponent(Component c,double scale) {
        new开发者_高级运维 PrintUtilities(c,scale).print();
    }

    public PrintUtilities(Component componentToBePrinted, double scale) {
        this.componentToBePrinted = componentToBePrinted;
        this.scale = scale;

    }

    public void print() {
        PrinterJob printJob = PrinterJob.getPrinterJob();
        printJob.setPrintable(this);
        if (printJob.printDialog())
            try {
                printJob.print();
            } catch(PrinterException pe) {
                System.out.println("Error printing: " + pe);
            }
    }

    public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
        if (pageIndex > 0) {
            return(NO_SUCH_PAGE);
        } else {
            Graphics2D g2d = (Graphics2D)g;
            g2d.scale(scale, scale);
            g2d.translate(pageFormat.getImageableX(),pageFormat.getImageableY());
            disableDoubleBuffering(componentToBePrinted);
            componentToBePrinted.paint(g2d);
            enableDoubleBuffering(componentToBePrinted);
            return(PAGE_EXISTS);
        }
    }

}

When i do what i have, i have to individually click "print" for each component that is going to be printed, any ideas of what i can do to print all the components in a single printerjob?

I also need to center the component on the page, i tried doing:

g2d.translate((pageFormat.getImageableWidth()-componentToBePrinted.getWidth)/2,
              pageFormat.getImageableY());

but in some cases the width of the component is larger than the imageable width, any ideas?


Try adding each JPanel to another JPanel:

JPanel wrapper = new JPanel();

for(JPanel panel : yourPanels){
     wrapper.add(panel);
}

PrintUtilities.printComponent(wrapper, scale);


You can send Component con[] as an parameter for print job and then apply printutil recursion accordingly

Pass all panels in array and change the indexing in the print() function .

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜