April 11, 2009

Published April 11, 2009 by

Launch Default Browser, Mail Client or Desktop Applications to Open, Edit, Print Files from Java Application

The java.awt.Desktop class allows a Java application to launch associated applications registered on the native desktop to handle a URI or a file.
Supported operations include:
• launching the user-default browser to show a specified URI;
• launching the user-default mail client with an optional mailto URI;
• launching a registered application to open, edit or print a specified file.
A sample Java program is given here to use the operations of the Desktop class (JDK 6 is required). The output screen of the program is as below:




Some important program segments are discussed here:

private Desktop desktop = Desktop.getDesktop();


Static method getDesktop returns the Desktop instance of the current browser context. On some platforms the Desktop API may not be supported; use the isDesktopSupported() method to determine if the current desktop is supported.



String uri=txtURL.getText();
desktop.browse(new URI(uri));

This code launches the default browser to display a 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. The application is determined from the protocol and path of the URI, as defined by the URI class.



String mailToURI="mailto:"+txtMailTo.getText(); desktop.mail(new URI(mailToURI));

This code launches the mail composing window of the user default mail client, filling the message fields specified by a mailto: URI.



JFileChooser fileChooser = new JFileChooser();
int choice = fileChooser.showOpenDialog(this);
if (choice == JFileChooser.APPROVE_OPTION) {
    file = fileChooser.getSelectedFile();
    txtFile.setText(file.getPath());
}


These lines of code provide a simple mechanism for the user to choose a file and shows the specified file path in a text field.



desktop.open(file);


This code launches the associated application to open the specified file. If the file is a directory, the file manager of the current platform is launched to open it.



desktop.edit(file);


This code launches the associated editor application for the specified file and opens the file for editing.



desktop.print(file);


This code prints the specified file with the native desktop printing facility, using the associated application's print command.

The full source code for the above operations:


import java.awt.Desktop;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.WindowConstants;

public class ApplicationLauncherUI extends JDialog {

    public ApplicationLauncherUI(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    private void initComponents() {

        pnlFile = new JPanel();
        lblFile = new JLabel();
        txtFile = new JTextField();
        btnBrowse = new JButton();
        btnPrint = new JButton();
        btnEdit = new JButton();
        btnOpen = new JButton();
        pnlBrowserMailClient = new JPanel();
        lblURL = new JLabel();
        txtURL = new JTextField();
        btnLaunchBrowser = new JButton();
        lblMailTo = new JLabel();
        txtMailTo = new JTextField();
        btnMailClient = new JButton();

        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Launch Default Applications");
        getContentPane().setLayout(null);

        pnlFile.setBorder(
                BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "File"));
        pnlFile.setLayout(null);

        lblFile.setText("File");
        pnlFile.add(lblFile);
        lblFile.setBounds(10, 30, 30, 14);
        pnlFile.add(txtFile);
        txtFile.setBounds(50, 30, 510, 20);

        btnBrowse.setText("Browse");
        btnBrowse.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                btnBrowseActionPerformed(evt);
            }
        });
        pnlFile.add(btnBrowse);
        btnBrowse.setBounds(570, 30, 110, 23);

        btnPrint.setText("Print");
        btnPrint.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                btnPrintActionPerformed(evt);
            }
        });
        pnlFile.add(btnPrint);
        btnPrint.setBounds(360, 60, 80, 23);

        btnEdit.setText("Edit");
        btnEdit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                btnEditActionPerformed(evt);
            }
        });
        pnlFile.add(btnEdit);
        btnEdit.setBounds(260, 60, 80, 23);

        btnOpen.setText("Open");
        btnOpen.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                btnOpenActionPerformed(evt);
            }
        });
        pnlFile.add(btnOpen);
        btnOpen.setBounds(150, 60, 80, 23);

        getContentPane().add(pnlFile);
        pnlFile.setBounds(10, 20, 690, 100);

        pnlBrowserMailClient.setBorder(BorderFactory
                .createTitledBorder(BorderFactory.createEtchedBorder(), "Browser and Mail Client"));
        pnlBrowserMailClient.setLayout(null);

        lblURL.setText("URL");
        pnlBrowserMailClient.add(lblURL);
        lblURL.setBounds(10, 40, 30, 14);

        txtURL.setText("http://");
        pnlBrowserMailClient.add(txtURL);
        txtURL.setBounds(60, 40, 480, 20);

        btnLaunchBrowser.setText("Launch Browser");
        btnLaunchBrowser.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                btnLaunchBrowserActionPerformed(evt);
            }
        });
        pnlBrowserMailClient.add(btnLaunchBrowser);
        btnLaunchBrowser.setBounds(550, 40, 130, 23);

        lblMailTo.setText("Mail To");
        pnlBrowserMailClient.add(lblMailTo);
        lblMailTo.setBounds(10, 90, 40, 14);
        pnlBrowserMailClient.add(txtMailTo);
        txtMailTo.setBounds(60, 90, 480, 20);

        btnMailClient.setText("Mail Client");
        btnMailClient.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                btnMailClientActionPerformed(evt);
            }
        });
        pnlBrowserMailClient.add(btnMailClient);
        btnMailClient.setBounds(550, 90, 130, 23);

        getContentPane().add(pnlBrowserMailClient);
        pnlBrowserMailClient.setBounds(10, 130, 690, 140);

        pack();
    }//

    private void btnLaunchBrowserActionPerformed(ActionEvent evt) {

        try {
            String uri = txtURL.getText();
            //Launch the default browser to display a URI
            desktop.browse(new URI(uri));
        } catch (IOException ioe) {
            JOptionPane.showMessageDialog(this, "An error occured! Cannot launch");
        } catch (URISyntaxException ex) {
            JOptionPane.showMessageDialog(this, "Wrong URL");
        }
    }

    private void btnPrintActionPerformed(ActionEvent evt) {
        try {
            /*Print a file with the native desktop printing facility,
            using the associated application's print command*/
            desktop.print(file);
        } catch (IOException ioe) {
            JOptionPane.showMessageDialog(this, "An error occured! Cannot launch");
        }
    }

    private void btnBrowseActionPerformed(ActionEvent evt) {
        JFileChooser fileChooser = new JFileChooser();
        int choice = fileChooser.showOpenDialog(this);
        if (choice == JFileChooser.APPROVE_OPTION) {
            file = fileChooser.getSelectedFile();
            txtFile.setText(file.getPath());
        }
    }

    private void btnOpenActionPerformed(ActionEvent evt) {
        try {
            // Launch the associated application to open the file
            desktop.open(file);
        } catch (IOException ioe) {
            JOptionPane.showMessageDialog(this, "An error occured! Cannot launch");
        }
    }

    private void btnEditActionPerformed(ActionEvent evt) {
        try {
            //Launch the associated editor application and opens a file for editing
            desktop.edit(file);
        } catch (IOException ioe) {
            JOptionPane.showMessageDialog(this, "An error occured! Cannot launch");
        }
    }

    private void btnMailClientActionPerformed(ActionEvent evt) {

        try {
            String mailToURI = "mailto:" + txtMailTo.getText();
            //Launch the mail composing window of the user default mail client
            desktop.mail(new URI(mailToURI));
        } catch (IOException ioe) {
            JOptionPane.showMessageDialog(this, "An error occured! Cannot launch");
            ioe.printStackTrace();
        } catch (URISyntaxException ex) {
            JOptionPane.showMessageDialog(this, "Wrong Mail To Address");
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                ApplicationLauncherUI dialog = new ApplicationLauncherUI(new JFrame(), true);
                dialog.addWindowListener(new WindowAdapter() {
                    public void windowClosing(WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setSize(715, 330);
                dialog.setVisible(true);
            }
        });
    }

    private JButton btnBrowse;
    private JButton btnEdit;
    private JButton btnLaunchBrowser;
    private JButton btnMailClient;
    private JButton btnOpen;
    private JButton btnPrint;
    private JLabel lblFile;
    private JLabel lblMailTo;
    private JLabel lblURL;
    private JPanel pnlBrowserMailClient;
    private JPanel pnlFile;
    private JTextField txtFile;
    private JTextField txtMailTo;
    private JTextField txtURL;

    private File file;
    private Desktop desktop = Desktop.getDesktop();
}