Home Tutorial Java Swing Java Swing Open Browser


Share on Google+Share on Google+
Java Swing Open Browser
Posted on: May 13, 2010 at 12:00 AM
In this section, you will learn how to create an example that will open the specified url on the browser using java swing.

Java Swing Open Browser

Java provides different methods to develop useful applications. In this section, you will learn how to create an example that will open the specified url on the browser using java swing. This example will really helpful if you need to show the help window for your application. Here, we have allowed the user to enter url of their choice. As the user clicked the button, the method exec("rundll32 url.dll,FileProtocolHandler ") of Runtime class opens the default browser with the specified url.

Here is the code:

1) OpenBrowser.java:

import javax.swing.*;
import java.lang.reflect.Method;

public class OpenBrowser {
	public static void openURL(String url) {
		String osName = System.getProperty("os.name");
		try {
			if (osName.startsWith("Windows"))
						"rundll32 url.dll,FileProtocolHandler " + url);
			else {
				String[] browsers = { "firefox", "opera", "konqueror",
						"epiphany", "mozilla", "netscape" };
				String browser = null;
				for (int count = 0; count < browsers.length && browser == null; count++)
					if (Runtime.getRuntime().exec(
							new String[] { "which", browsers[count] })
							.waitFor() == 0)
						browser = browsers[count];
				Runtime.getRuntime().exec(new String[] { browser, url });
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, "Error in opening browser"
					+ ":\n" + e.getLocalizedMessage());

2) Browser.java:

import javax.swing.*;
import java.awt.event.*;

public class Browser {
	public static void main(String[] args) {
		JFrame frame = new JFrame();
		JPanel panel = new JPanel();
		final JTextField url = new JTextField(20);
		JButton button = new JButton("Open Browser");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
		panel.add(new JLabel("URL:"));


After specifying the url, when you click the button, the browser will get opened with the specified url:


Related Tags for Java Swing Open Browser:

Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: May 13, 2010

Recommend the tutorial

Advertisements Advertisements