【问题标题】:How to detect whether Printer is attached to your computer or not in Java?如何在 Java 中检测打印机是否连接到您的计算机?
【发布时间】:2009-09-07 06:22:07
【问题描述】:

我正在用 Swing Java 创建一个 GUI。我必须使用一个按钮“打印”,它将直接开始打印我设置的文件,而无需打开默认的打印对话框。 我必须先检查打印机是否连接到我的计算机上?

【问题讨论】:

  • 只是想评论一下,如果这个 GUI 仅供您个人使用,那很好。但是,如果您打算让其他人使用它,那么只为用户决定使用哪种打印机是不好的设计。可以去 36" 绘图仪。另外,你的最后一句话是一个带问号的陈述。这不是一个真正的问题吗?
  • 刚刚完成我的回答以检查打印机是否已连接

标签: java


【解决方案1】:

可能正在使用PrintServiceLookup

此类的实现为特定类型的打印服务(通常等同于打印机)提供查找服务。

DocFlavor flavor = DocFlavor.INPUT_STREAM.POSTSCRIPT;
PrintRequestAttributeSet aset = new HashPrintRequestHashAttributeSet();
aset.add(MediaSizeName.ISO_A4);
PrintService[] pservices =PrintServiceLookup.lookupPrintServices(flavor, aset);
if (pservices.length > 0) {
    DocPrintJob pj = pservices[0].createPrintJob();
    //....
}

注意:如果有打印机,PrintService 的数量应至少为一个。如果有实际打印机,则可能至少有 2 个,因为您可以在计算机上安装纯软件打印机。另见this thread

取决于平台和jdk,它可以有some bug,否则,下面的方法应该至少列出打印机:

import java.awt.print.*;
import javax.print.*;
import javax.print.attribute.*;
import java.text.*;
import javax.print.attribute.standard.*;

public class ShowPrinters {

    public ShowPrinters() {
    }

    public static void main(String[] args) {
        DocFlavor myFormat = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
        PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
        PrintService[] services =PrintServiceLookup.lookupPrintServices(myFormat, aset);
        System.out.println("The following printers are available");
        for (int i=0;i<services.length;i++) {
            System.out.println("  service name: "+services[i].getName());
        }
    }
}

在这个eclipse code source,你已经看到使用PrinterState来检查打印机是否真的连接了:

AttributeSet attributes = new HashPrintServiceAttributeSet(
    new PrinterName(printerName, Locale.getDefault()));
PrintService[] services = PrintServiceLookup.lookupPrintServices(
    DocFlavor.SERVICE_FORMATTED.PRINTABLE,
    attributes);
PrintService printService = services[0];
PrintServiceAttributeSet printServiceAttributes = printService.getAttributes();
PrinterState printerState = (PrinterState) printServiceAttributes.get(PrinterState.class);

检查printerState 是否不为空。注意:这可能还不够(请参阅this thread)。

【讨论】:

  • 是的,我在这里得到了打印机的名称,但我的打印机没有物理连接到我的计算机上。在继续之前我应该​​如何检查它?
  • 我认为只要打印机已“安装”在盒子上,无论是本地打印机还是网络打印机,它都应该可以通过上述代码使用。我会对其进行测试,但目前我没有任何一个选项可用。 :-)
  • @VonC 你知道为什么即使打印机已打开并实际连接,printerState 可能始终为空吗?
  • @whizzzkey 不,我不知道。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-13
  • 2012-03-25
  • 2021-07-10
  • 1970-01-01
  • 1970-01-01
  • 2013-12-04
相关资源
最近更新 更多