Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

JLabel hyperlink to open browser at correct URL

680557Dec 30 2011 — edited Dec 30 2011
I need to create a label with Java Swing that is clickable and able to open the default browser on the desktop and redirect it to a specific url. My code is able to open up the browser but not redirecting it to the correct url (the default home page is loaded). My test code:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.IOException;
import java.net.*;

public class LinkTest extends JFrame {

public LinkTest() {
JPanel p = new JPanel();

JLabel link = new JLabel("Click here");
link.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
link.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() > 0) {
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
try {
URI uri = new URI("http://www.bbc.co.uk");
desktop.browse(uri);
} catch (IOException ex) {
ex.printStackTrace();
} catch (URISyntaxException ex) {
ex.printStackTrace();
}
}
}
}
});
p.add(link);
getContentPane().add(BorderLayout.NORTH, p);
}

public static void main(String[] args) {
LinkTest linkTest = new LinkTest();
linkTest.setSize(640,100);
linkTest.show();
}
}

How can I have a default browser open and redirect to the correct URL with Java Swing?
I'm using Java 6 + Ubuntu 11.10 + Chrome 16

Thanks
Julio

Edited by: user6377515 on Dec 30, 2011 4:32 AM
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jan 27 2012
Added on Dec 30 2011
3 comments
1,119 views