Skip to main content

Cute and Pasty: Browser Opener

Posted by evanx on October 29, 2006 at 11:58 AM PST

I'll maintain this page at this
permalink.

Here's one way to popup a browser (in Windows), or otherwise prompt the user
with the URL, ready for cutting and pasting into your browser.

public class BrowserOpener {
   
    public void showDocument(String url) {
        if (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) {
            try {
                Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
                return;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        showDocumentRequest(url);
    }
   
    protected void showDocumentRequest(String url) {
        JTextField textField = new JTextField(url);
        final JDialog dialog = new JDialog((JFrame) null, "Browser", true);
        dialog.setLayout(new GridBagLayout());
        JPanel panel = new JPanel(new GridBagLayout());
        String message = "Please paste the following URL into your browser. " +
                "Press Control X to cut.";
        panel.add(new JLabel(message), Gbc.xyi(0, 0, 2));
        panel.add(textField, Gbc.xyi(0, 1, 2).horizontal());
        dialog.add(panel, Gbc.xyi(0, 0, 4).horizontal());
        dialog.setBounds(100, 200, 700, 250);
        dialog.pack();
        dialog.setMinimumSize(new Dimension(600, 40));
        textField.setSelectionEnd(url.length());
        textField.getDocument().addDocumentListener(new DocumentListener() {
            public void changedUpdate(DocumentEvent e) {
            }
            public void insertUpdate(DocumentEvent e) {
            }
            public void removeUpdate(DocumentEvent e) {
                dialog.dispose();
            }
        });
        dialog.setVisible(true);
    }
   
    public static void main(String[] args) {
        new BrowserOpener().showDocumentRequest("http://aptframework.dev.java.net");
        System.exit(1);
    }
}

This uses gridbaglady.dev.java.net
ie. Gbc.java.

The following dialog will popup. We already select the URL text, so the user need just press
Control X, and it will dispose, thanks to the DocumentListener.

browserOpener.png

If you
got some ideas on improving this, eg. for other OSes, and other approaches eg. JNLP's
BasicService, please comment, and i'll extend this page. How do you do it?

Related Topics >>