Update . I embellished the SwingLink class and added additional features; An updated copy can be found here: https://bitbucket.org/dimo414/jgrep/src/tip/src/grep/SwingLink.java
@McDowell's answer is great, but there are a few things that can be improved. In particular, text other than a hyperlink can be clicked, and it still looks like a button, although some style elements have been changed / hidden. While accessibility is important, a consistent user interface is also provided.
So, I put together a class extending JLabel based on McDowell code. It is self-sufficient, correctly processes errors and looks more like a link:
public class SwingLink extends JLabel { private static final long serialVersionUID = 8273875024682878518L; private String text; private URI uri; public SwingLink(String text, URI uri){ super(); setup(text,uri); } public SwingLink(String text, String uri){ super(); setup(text,URI.create(uri)); } public void setup(String t, URI u){ text = t; uri = u; setText(text); setToolTipText(uri.toString()); addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { open(uri); } public void mouseEntered(MouseEvent e) { setText(text,false); } public void mouseExited(MouseEvent e) { setText(text,true); } }); } @Override public void setText(String text){ setText(text,true); } public void setText(String text, boolean ul){ String link = ul ? "<u>"+text+"</u>" : text; super.setText("<html><span style=\"color: #000099;\">"+ link+"</span></html>"); this.text = text; } public String getRawText(){ return text; } private static void open(URI uri) { if (Desktop.isDesktopSupported()) { Desktop desktop = Desktop.getDesktop(); try { desktop.browse(uri); } catch (IOException e) { JOptionPane.showMessageDialog(null, "Failed to launch the link, your computer is likely misconfigured.", "Cannot Launch Link",JOptionPane.WARNING_MESSAGE); } } else { JOptionPane.showMessageDialog(null, "Java is not able to launch links on your computer.", "Cannot Launch Link", JOptionPane.WARNING_MESSAGE); } } }
You can also, for example, change the color of the link to purple by clicking if it is useful. All this by itself, you just call:
SwingLink link = new SwingLink("Java", "http://java.sun.com"); mainPanel.add(link);
dimo414 Dec 23 '10 at 11:53 2010-12-23 11:53
source share