Documentation

The Java™ Tutorials
Hide TOC
How to Integrate with the Desktop Class如何与Desktop类集成
Trail: Creating a GUI With Swing
Lesson: Using Other Swing Features使用其他回转特征

How to Integrate with the Desktop Class如何与桌面类集成

Java™ Standard Edition version 6 narrows the gap between performance and integration of native applications and Java applications. Java™软件;Standard Edition版本6缩小了本地应用程序和Java应用程序的性能和集成之间的差距。Along with the new system tray functionality, splash screen support, and enhanced printing for JTables, Java SE version 6 provides the Desktop API (java.awt.Desktop) API, which allows Java applications to interact with default applications associated with specific file types on the host platform.除了新的系统托盘功能、闪屏支持和增强的JTables打印之外,Java SE版本6还提供了桌面API(java.awt.Desktop)API,它允许Java应用程序与主机平台上与特定文件类型关联的默认应用程序交互。

New functionality is provided by the Desktop class. Desktop类提供了新功能。The API arises from the JDesktop Integration Components (JDIC) project. 该API源于JDesktop集成组件(JDIC)项目。The goal of the JDIC project is to make "Java technology-based applications first-class citizens" of the desktop, enabling seamless integration. JDIC项目的目标是使桌面“基于Java技术的应用程序成为一流公民”,实现无缝集成。JDIC provides Java applications with access to functionalities and facilities provided by the native desktop. JDIC为Java应用程序提供了对本机桌面提供的功能和设施的访问。Regarding the new Desktop API, this means that a Java application can perform the following operations:关于新的桌面API,这意味着Java应用程序可以执行以下操作:


Note: 

The Desktop API uses the host operating system's file associations to launch applications associated with specific file types. 桌面API使用主机操作系统的文件关联来启动与特定文件类型关联的应用程序。For example, if OpenDocument text (.odt) file extensions are associated with the OpenOffice Writer application, a Java application could launch OpenOffice Writer to open, edit, or even print files with that association. 例如,如果OpenDocument文本(.odt)文件扩展名与OpenOffice Writer应用程序相关联,Java应用程序可以启动OpenOffice Wliter以打开、编辑甚至打印具有该关联的文件。Depending on the host system, different applications may be associated with different actions. 根据主机系统的不同,不同的应用程序可能与不同的操作相关联。For example, if a particular file cannot be printed, check first whether its extension has a printing association on the given operating system.例如,如果无法打印特定文件,请首先检查其扩展名在给定操作系统上是否具有打印关联。


Use the isDesktopSupported() method to determine whether the Desktop API is available. 使用isDesktopSupported()方法确定桌面API是否可用。On the Solaris Operating System and the Linux platform, this API is dependent on Gnome libraries. 在Solaris操作系统和Linux平台上,此API依赖于Gnome库。If those libraries are unavailable, this method will return false. 如果这些库不可用,此方法将返回falseAfter determining that the Desktop API is supported, that is, the isDesktopSupported() returns true, the application can retrieve a Desktop instance using the static method getDesktop().确定支持Desktop API后,即isDesktopSupported()返回true,应用程序可以使用静态方法getDesktop()检索Desktop实例。

If an application runs in an environment without a keyboard, mouse, or monitor (a "headless" environment), the getDesktop() method throws a java.awt.HeadlessException.如果应用程序在没有键盘、鼠标或监视器的环境中运行(“headless”环境),getDesktop()方法将抛出java.awt.HeadlessException

Once retrieved, the Desktop instance allows an application to browse, mail, open, edit, or even print a file or URI, but only if the retrieved Desktop instance supports these activities. 一旦检索到,Desktop实例允许应用程序浏览、发送邮件、打开、编辑甚至打印文件或URI,但前提是检索到的Desktop示例支持这些活动。Each of these activities is called an action, and each is represented as a Desktop.Action enumeration instance:这些活动中的每一个都称为一个操作,每个都表示为一个Desktop.Action枚举实例:

Different applications may be registered for these different actions even on the same file type. 即使在同一文件类型上,也可以为这些不同的操作注册不同的应用程序。For example, the Firefox browser may be launched for the OPEN action, Emacs for the EDIT action, and yet a different application for the PRINT action. 例如,可以为OPEN操作启动Firefox浏览器,为EDIT操作启动Emacs,为PRINT操作启动不同的应用程序。Your host desktop's associations are used to determine which application should be invoked. 主机桌面的关联用于确定应调用哪个应用程序。The ability to manipulate desktop file associations is not possible with the current version of the Desktop API in JDK 6, and those associations can be created or changed only with platform-dependent tools at this time.JDK 6中当前版本的桌面API无法操作桌面文件关联,此时只能使用依赖于平台的工具创建或更改这些关联。

The following example shows the capabilities mentioned above.以下示例显示了上述功能。


Try this: 
  1. Compile and run the example, consult the example index.编译并运行示例,查阅示例索引
  2. The DesktopDemo dialog box will appear. 将出现DesktopDemo对话框。
    DesktopDemo application.
  3. Enter an URI value into the URI text field, for example – 在URI文本字段中输入URI值,例如–https://docs.oracle.com/javase/tutorial.
  4. Press the Launch Browser button.按Launch Browser(启动浏览器)按钮。
  5. Ensure that the default browser window opens and the Tutorial main page is loaded.确保打开默认浏览器窗口并加载教程主页。
  6. Change URI to an arbitrary value, press the Launch Browser button, and ensure that the web page you requested is loaded successfully.将URI更改为任意值,按Launch Browser按钮,并确保成功加载您请求的网页。
  7. Switch back to the DesktopDemo dialog box and enter a mail recipient name in the E-mail text field. 切换回DesktopDemo对话框,并在电子邮件文本字段中输入邮件收件人姓名。You can also use the mailto scheme supporting CC, BCC, SUBJECT, and BODY fields, for example – duke@example.com?SUBJECT=Hello Duke!.您还可以使用支持CC、BCC、SUBJECT和BODY字段的mailto方案,例如duke@example.com?SUBJECT=Hello Duke!
  8. Press the Launch Mail button.按“启动邮件”按钮。
  9. The compositing dialog box of the default email client will appear. 将显示默认Electron邮件客户端的合成对话框。Be sure that the To and Subject fields are as follows. 确保“收件人”和“主题”字段如下所示。
    DesktopDemo application.
  10. You can continue to compose a message or try to enter different combinations of the mail schema in the E-mail field.您可以继续撰写邮件,也可以尝试在“Electron邮件”字段中输入邮件模式的不同组合。
  11. Switch back to the DesktopDemo dialog box and press the ellipsis button to choose any text file.切换回DesktopDemo对话框,然后按省略号按钮选择任何文本文件。
  12. Select either Open, Edit, or Print to set the type of operation, then press the Launch Application button.选择打开、编辑或打印以设置操作类型,然后按启动应用程序按钮。
  13. Be sure that operation completes correctly. 确保操作正确完成。Try other file formats, for example .odt, .html, .pdf. 尝试其他文件格式,例如.odt.html.pdfNote: If you try to edit .pdf file, the DesktopDemo returns the following message: 注意:如果您尝试编辑.pdf文件,DesktopDemo会返回以下消息:Cannot perform the given operation to the <file name> file

The following code snippets provide more details on the DeskDemo application implementation. 以下代码片段提供了有关DeskDemo应用程序实现的更多详细信息。The DesktopDemo constructor disables the few components right after instantiating the UI and checks whether the Desktop API is available.DesktopDemo构造函数在实例化UI后立即禁用少数组件,并检查Desktop API是否可用。

public DesktopDemo() {
        // init all GUI components
        initComponents();
        // disable buttons that launch browser, email client,
        // disable buttons that open, edit, print files
        disableActions();
        // before any Desktop APIs are used, first check whether the API is
        // supported by this particular VM on this particular host
        if (Desktop.isDesktopSupported()) {
            desktop = Desktop.getDesktop();
            // now enable buttons for actions that are supported.
            enableSupportedActions();
        }
        ...

    /**
     * Disable all graphical components until we know
     * whether their functionality is supported.
     */
    private void disableActions() {
        txtBrowserURI.setEnabled(false);
        btnLaunchBrowser.setEnabled(false);
        
        txtMailTo.setEnabled(false);
        btnLaunchEmail.setEnabled(false);
        
        rbEdit.setEnabled(false);
        rbOpen.setEnabled(false);
        rbPrint.setEnabled(false);

        txtFile.setEnabled(false);
        btnLaunchApplication.setEnabled(false);        
    }
    

   ...

Once a Desktop object is acquired, you can query the object to find out which specific actions are supported. 获取Desktop对象后,可以查询该对象以了解支持哪些特定操作。If the Desktop object does not support specific actions, or if the Desktop API itself is unsupported, DesktopDemo simply keeps the affected graphical components disabled.如果桌面对象不支持特定操作,或者桌面API本身不受支持,DesktopDemo只会将受影响的图形组件保持为禁用状态。

/**
     * Enable actions that are supported on this host.
     * The actions are the following: open browser, 
     * open email client, and open, edit, and print
     * files using their associated application.
     */
    private void enableSupportedActions() {
        if (desktop.isSupported(Desktop.Action.BROWSE)) {
            txtBrowserURI.setEnabled(true);
            btnLaunchBrowser.setEnabled(true);
        }
        
        if (desktop.isSupported(Desktop.Action.MAIL)) {
            txtMailTo.setEnabled(true);
            btnLaunchEmail.setEnabled(true);
        }

        if (desktop.isSupported(Desktop.Action.OPEN)) {
            rbOpen.setEnabled(true);
        }
        if (desktop.isSupported(Desktop.Action.EDIT)) {
            rbEdit.setEnabled(true);
        }
        if (desktop.isSupported(Desktop.Action.PRINT)) {
            rbPrint.setEnabled(true);
        }
        
        if (rbEdit.isEnabled() || rbOpen.isEnabled() || rbPrint.isEnabled()) {
            txtFile.setEnabled(true);
            btnLaunchApplication.setEnabled(true);
        }
    }

The browse(uri) method can throw a variety of exceptions, including a NullPointerException if the URI is null, and an UnsupportedOperationException if the BROWSE action is unsupported. browse(uri)方法可以引发各种异常,包括uri为null时的NullPointerException,以及不支持browse操作时的UnsupportedOperationExceptionThis method can throw an IOException if the default browser or application cannot be found or launched, and a SecurityException if a security manager denies the invocation.如果无法找到或启动默认浏览器或应用程序,此方法会引发IOException,如果安全管理器拒绝调用,则会引发SecurityException。

private void onLaunchBrowser(ActionEvent evt) {
        URI uri = null;
        try {
            uri = new URI(txtBrowserURI.getText());
            desktop.browse(uri);
        } catch(IOException ioe) {
            System.out.println("The system cannot find the " + uri + 
                " file specified");
            //ioe.printStackTrace();
        } catch(URISyntaxException use) {
            System.out.println("Illegal character in path");
            //use.printStackTrace();
        }
    }

Applications can launch the host's default email client, if that action is supported, by calling the mail(uriMailTo) method of this Desktop instance.如果支持该操作,应用程序可以通过调用此桌面实例的mail(uriMailTo)方法来启动主机的默认电子邮件客户端。

private void onLaunchMail(ActionEvent evt) {
        String mailTo = txtMailTo.getText();
        URI uriMailTo = null;
        try {
            if (mailTo.length() > 0) {
                uriMailTo = new URI("mailto", mailTo, null);
                desktop.mail(uriMailTo);
            } else {
                desktop.mail();
            }
        } catch(IOException ioe) {
            ioe.printStackTrace();
        } catch(URISyntaxException use) {
            use.printStackTrace();
        }
    }

Java applications can open, edit, and print files from their associated application using the open(), edit(), and print() methods of the Desktop class, respectively.Java应用程序可以分别使用Desktop类的open()edit()print()方法从关联的应用程序中打开、编辑和打印文件。

private void onLaunchDefaultApplication(ActionEvent evt) {
        String fileName = txtFile.getText();
        File file = new File(fileName);
        
        try {
            switch(action) {
                case OPEN:
                    desktop.open(file);
                    break;
                case EDIT:
                    desktop.edit(file);
                    break;
                case PRINT:
                    desktop.print(file);
                    break;
            }
        } catch (IOException ioe) {
            //ioe.printStackTrace();
            System.out.println("Cannot perform the given operation 
                to the " + file + " file");
        }
    }

The complete code for this demo is available in the DesktopDemo.java file.DesktopDemo.java文件中提供了此演示的完整代码。

The Desktop API

The Desktop class allows Java applications to launch the native desktop applications that handle URIs or files.Desktop类允许Java应用程序启动处理URI或文件的本机桌面应用程序。

Method方法 Purpose意图
isDesktopSupported() Tests whether this class is supported on the current platform. 测试当前平台上是否支持此类。If it is supported, use getDesktop() to retrieve an instance.如果支持,请使用getDesktop()检索实例。
getDesktop() Returns the Desktop instance of the current browser context. 返回当前浏览器上下文的Desktop实例。On some platforms the Desktop API may not be supported. 在某些平台上,桌面API可能不受支持。Use the isDesktopSupported() method to determine if the current desktop is supported.使用isDesktopSupported()方法确定当前桌面是否受支持。
isSupported(Desktop.Action) Tests whether an action is supported on the current platform. 测试当前平台上是否支持某个操作。Use the following constants of the Desktop.Action enum: BROWSE, EDIT, MAIL, OPEN, PRINT.使用Desktop.Action枚举的以下常量:BROWSEEDITMAILOPENPRINT
browse(URI) Launches the default browser to display a URI. 启动默认浏览器以显示URI。If the default browser is not able to handle the specified URI, the application registered for handling URIs of the specified type is invoked. 如果默认浏览器无法处理指定的URI,则会调用注册用于处理指定类型URI的应用程序。The application is determined from the protocol and path of the URI, as defined by the URI class.应用程序由URI类定义的URI的协议和路径确定。
mail(URI) Launches the mail composing window of the user default mail client, filling the message fields specified by a mailto: URI.启动用户默认邮件客户端的邮件撰写窗口,填充mailto:URI指定的消息字段。
open(File) Launches the associated application to open a file.启动关联的应用程序以打开文件。
edit(File) Launches the associated editor application and opens a file for editing.启动关联的编辑器应用程序并打开一个文件进行编辑。
print(File) Prints a file with the native desktop printing facility, using the associated application's print command.使用关联应用程序的打印命令,使用本机桌面打印工具打印文件。

Examples That Use Desktop API使用桌面API的示例

The following table lists the example that uses the Desktop class integration.下表列出了使用Desktop类集成的示例。

Example实例 Where Described描述位置 Notes笔记
DesktopDemo This section本节 Launches the host system's default browser with the specified URI and default email client; launches an application to open, edit, or print a file.使用指定的URI和默认电子邮件客户端启动主机系统的默认浏览器;启动应用程序以打开、编辑或打印文件。

Previous page: Using Other Swing Features
Next page: How to Create Translucent and Shaped Windows