While working on any Java project, sometimes you want to add a button that can open a specific URL on browser of the computer. You can add any link like social media, blog, website, forum, etc. This can be easily done in Java with the following -
1. Add the following libraries at the starting of your project.
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
2. Now add a JButton by which you want to open URL on browser.
JButton gitbt = new JButton("Github");
gitbt.setBounds(5,150, 190,40);
3. Add a action listner to that button.
gitbt.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
}
});
4. Now use this main code inside that action listner which actually opens the URL.
if (Desktop.isDesktopSupported()) {
{
Desktop dsktp = Desktop.getDesktop();
try {
desk.browse(new URI("https://pvdocs.blogspot.com/"));
} catch (IOException ex) {
throw new RuntimeException(ex);
} catch (URISyntaxException ex) {
throw new RuntimeException(ex);
}
}
}
Explanation of above code -
In the starting, the code will check if the operating system is supported or not. Supported operating systems are - Linux, Windows, MacOS.
Then, it will create a new instance of Desktop class and store it in the dsktp.
After that, there is try-catch block. It will try to open the URL and if any exception is thrown, it will rethrow it as RuntimeException.