Open Website URL in Default Browser in Java

0
71

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.

  1. import java.awt.Desktop;
  2. import java.io.IOException;
  3. import java.net.URI;
  4. import java.net.URISyntaxException;
  5. import java.util.logging.Level;
  6. import java.util.logging.Logger;

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

  1. String url = jTextField1.getText();
  2. if (Desktop.isDesktopSupported()) {
  3. try {
  4. // Windows
  5. Desktop.getDesktop().browse(new URI(url));
  6. } catch (IOException | URISyntaxException ex) {
  7. Logger.getLogger(WebBrowser.class.getName()).log(Level.SEVERE, null, ex);
  8. }
  9. } else {
  10. // Ubuntu
  11. Runtime runtime = Runtime.getRuntime();
  12. try {
  13. runtime.exec("/usr/bin/firefox -new-window " + url);
  14. } catch (IOException ex) {
  15. Logger.getLogger(WebBrowser.class.getName()).log(Level.SEVERE, null, ex);
  16. }
  17. }

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

Facebook Comments

LEAVE A REPLY

Please enter your comment!
Please enter your name here