How can I open a link in default browser with a button click, along the lines of
button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { open("www.google.com"); // just what is the 'open' method? } });
?
connect method is called. When you do this you are initializing a communication link between your Java program and the URL over the network. For example, the following code opens a connection to the site example.com : try { URL myURL = new URL("http://example.com/"); URLConnection myURLConnection = myURL.
Creating a Hyperlink The code fragment that produces a hyperlink is shown in Example 20-1. Hyperlink link = new Hyperlink(); link. setText("http://example.com"); link.
net. URI: java. net. URI is used to Represent User Resource Identifier reference.
Use the Desktop#browse(URI) method. It opens a URI in the user's default browser.
public static boolean openWebpage(URI uri) { Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null; if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) { try { desktop.browse(uri); return true; } catch (Exception e) { e.printStackTrace(); } } return false; } public static boolean openWebpage(URL url) { try { return openWebpage(url.toURI()); } catch (URISyntaxException e) { e.printStackTrace(); } return false; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With