Reputation: 11
I am trying to create a GUI-based program in Java that has a 'Submit' button and when clicked, it takes you to a website.
I have read about the URL and URLConnection classes online and the connection to the website is established but the program does not open the link... This is what I have so far:
if(command.equals("Submit data"))
{
try {
URL myURL = new URL("http://google.com/");
URLConnection myURLConnection = myURL.openConnection();
myURLConnection.connect();
}
catch (IOException t) {
// openConnection() failed
// ...
}
}
The connection seems to be established but I want the program to open up the browser and take to the website.. I've tried everything and no luck.. Thank you
Upvotes: 1
Views: 4945
Reputation: 5903
You could either used a swing component like you can see in this thread --> Best Java/Swing browser component?
Otherwise use this snippet found at http://andy.ekiwi.de/?p=1026
public void openUrl(String url) throws IOException, URISyntaxException {
if(java.awt.Desktop.isDesktopSupported() ) {
java.awt.Desktop desktop = java.awt.Desktop.getDesktop();
if(desktop.isSupported(java.awt.Desktop.Action.BROWSE) ) {
java.net.URI uri = new java.net.URI(url);
desktop.browse(uri);
}
}
}
Upvotes: 4