Java Swing Open Browser


 

Java Swing Open Browser

In this section, you will learn how to create an example that will open the specified url on the browser using java swing.

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"))
				Runtime.getRuntime().exec(
						"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) {
				OpenBrowser.openURL(url.getText().trim());
			}
		});
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		panel.add(new JLabel("URL:"));
		panel.add(url);
		panel.add(button);
		frame.getContentPane().add(panel);
		frame.pack();
		frame.setVisible(true);
	}
}

Output:

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

Ads