Open Website URL in Default Browser in Java

0
456

This tutorial entitled “ Open Website URL Default Browser using Java ” will teach you on how you can create a program that can open any Website URL in Java and Netbeans.

This tutorial will use a jLable, jTextField, and jButton to perform the operation. In the code, we also use Desktop, IOException, URI, URISyntaxException, logging.Level, and logging.Logger libraries. Please follow the steps to complete this tutorial.

Open Website URL Default Browser using Java Steps

  1. Create a new jFrame Form and name it what you want.

2. Design your jFrame form just look like the image below.

3. Insert the following codes above your class to access the specified libraries.

[java]import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.logging.Level;
import java.util.logging.Logger;[/java]

4. Double click your browse button and add the codes below.

[java]String url = jTextField1.getText();
if (Desktop.isDesktopSupported()) {
try {
// Windows
Desktop.getDesktop().browse(new URI(url));
} catch (IOException | URISyntaxException ex) {
Logger.getLogger(WebBrowser.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
// Ubuntu
Runtime runtime = Runtime.getRuntime();
try {
runtime.exec(“/usr/bin/firefox -new-window ” + url);
} catch (IOException ex) {
Logger.getLogger(WebBrowser.class.getName()).log(Level.SEVERE, null, ex);
}
}[/java]

5. Run your program and it should look like the image below.

After you input the website URL and click the view button, the URL will open in your default browser. Remember that the provided code in the button will function both in Windows and Ubuntu operating system platform.

For more information, feel free to leave your comment below, use the contact page of this website or use my contact information.
Email: [email protected] | Cell. No.: 09468362375

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.