Refresh printers in Java while application is running

后端 未结 4 922
心在旅途
心在旅途 2021-01-18 12:45

As the title says, I would like to refresh the printers that are registered in the settings of the computer while my Java application is running. Normally, I can use P

4条回答
  •  囚心锁ツ
    2021-01-18 13:38

    There is no need to restart the application in order to refresh the list of print services.

    Here I found the solution:

    /**
     * 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;
            }
        }
    }
    

    Basically, the static class PrintServiceLookup.Services maintains the list of print services. So, if you remove this class from the AppContext, you force PrintServiceLookup to create a new instance again. Thus, the list of print services gets refreshed.

提交回复
热议问题