到目前为止,我所拥有的是:
// tab是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);
}
//这是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);
}
}
}
当我做我所拥有的,我必须单独点击“打印”每个要打印的组件,我可以做些什么来打印单个打印机工作中的所有组件?
我还需要将组件放在页面中心,我试着这样做:
g2d.translate((pageFormat.getImageableWidth()-componentToBePrinted.getWidth)/2,
pageFormat.getImageableY());
但在某些情况下,组件的宽度大于可成像宽度,任何想法?
答案 0 :(得分:0)
尝试将每个JPanel添加到另一个JPanel:
JPanel wrapper = new JPanel();
for(JPanel panel : yourPanels){
wrapper.add(panel);
}
PrintUtilities.printComponent(wrapper, scale);
答案 1 :(得分:0)
您可以发送Component con []作为打印作业的参数,然后相应地应用printutil递归
传递数组中的所有面板并更改print()函数中的索引。