Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open a link in browser with java button? [duplicate]

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

?

like image 662
Malasuerte94 Avatar asked Jun 10 '12 08:06

Malasuerte94


People also ask

How do you link a URL in Java?

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.

How do you make a clickable link in Java?

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.

Which URL should we type in the browser to run the project in Java?

net. URI: java. net. URI is used to Represent User Resource Identifier reference.


1 Answers

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; } 
like image 165
FThompson Avatar answered Oct 12 '22 16:10

FThompson