java实现打印购物清单jframe_java – 打印JFrame及其组件

这是一个简单的解决方案.我有一个实现可打印的Printer类,它将处理打印作业:

public static 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;

}

}

接下来,打印它:

JFrame yourComponent = new JFrame();

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(yourComponent), postformat);

if (pjob.printDialog()) {

pjob.print();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值