打印图形

来源:互联网 发布:日本留学 知乎 编辑:程序博客网 时间:2024/05/01 07:06
打印图形

  1、应用场景


  在实际应用中,我们还需要打印图形。譬如,我们有时需要将一个Java Applet的完整界面或一个应用程序窗体及其所包含的全部组件都打印出来,又应该如何实现呢?


  2、解决方法


  基本思路如下:在JavaComponent类及其派生类中都提供了printprintAll方法,只要设置好属性就可以直接调用这两个方法,从而实现对组件及图形的打印。


  /*打印指定的窗体及其包含的组件
*/
  
private void printFrameAction() {
  Toolkit kit = Toolkit.getDefaultToolkit(); //获取工具箱

  
Properties props = new Properties();
  props.put("awt.print.printer", "durango"); //设置打印属性

  
props.put("awt.print.numCopies", "2");
  
if (kit != null) {
  //获取工具箱自带的打印对象

  
PrintJob printJob = kit.getPrintJob(this, "Print Frame", props);
  
if (printJob != null) {
   Graphics pg = printJob.getGraphics(); //获取打印对象的图形环境

   
if (pg != null) {
    
try {
     this.printAll(pg); //打印该窗体及其所有的组件

    
}
    
finally {
     pg.dispose(); //注销图形环境

    
}
   
}
   printJob.end(); //结束打印作业

  
}
  
}
  
}

原创粉丝点击