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?
}
});
?
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;
}