正如标题所示,我想在 Java 应用程序运行时刷新在计算机设置中注册的打印机。
通常情况下,我可以使用PrinterJob.lookupPrintServices()
获得打印机。但是,这些仅在重新启动应用程序时才会刷新。我读过一些有关lookupPrintServices() 应该在新线程中完成才能获取打印机的内容。然而这不起作用,打印机列表保持不变。这以下链接表明这个问题应该在 Java 5.0 中得到解决,我做错了什么吗?
任何帮助深表感谢!
EDIT添加了 MWE。
public class MTPrinterTest extends Thread {
public static void main(String[] args) {
MTPrinterTest t1 = new MTPrinterTest();
t1.start();
try {
System.in.read();
} catch (Exception e){}
MTPrinterTest t2 = new MTPrinterTest();
t2.start();
}
public void run() {
PrinterJob printerJob;
PrintService[] printServices;
printerJob = PrinterJob.getPrinterJob();
printServices = printerJob.lookupPrintServices();
System.out.println("Number of servies found: " + printServices.length);
for (int i =0; i< printServices.length; i++)
System.out.println("--> Available Printer " + i + ": " + printServices[i]);
printerJob.printDialog();
}
}
无需重新启动应用程序即可刷新打印服务列表。
Here我找到了解决方案:
/**
* Printer list does not necessarily refresh if you change the list of
* printers within the O/S; you can run this to refresh if necessary.
*/
public static void refreshSystemPrinterList() {
Class<?>[] classes = PrintServiceLookup.class.getDeclaredClasses();
for (Class<?> clazz : classes) {
if ("javax.print.PrintServiceLookup$Services".equals(clazz.getName())) {
// sun.awt.AppContext.getAppContext().remove(clazz);
// Use reflection to avoid "Access restriction" error message
try {
Class<?> acClass = Class.forName("sun.awt.AppContext");
Object appContext = acClass.getMethod("getAppContext").invoke(null);
acClass.getMethod("remove", Object.class).invoke(appContext, clazz);
} catch (Exception e) {
}
break;
}
}
}
基本上,静态类PrintServiceLookup.Services
维护打印服务列表。因此,如果您从AppContext
,你强迫PrintServiceLookup
再次创建一个新实例。因此,打印服务列表被刷新。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)