Which is the best way to add a hyperlink in jLabel? I can get the view using html tags, but how to open the browser when the user clicks on it?
+2
A:
See here for how you can create a label with a hyperlink. I recommend however to use Bare Bones Browser Launcher for opening the browser.
kgiannakakis
2009-02-09 11:04:44
+1
A:
If <a href="link"> doesn't work, then:
- Create a JLabel and add a MouseListener (decorate the label to look like a hyperlink)
- Implement mouseClicked() event
- In the implementation of mouseClicked() event, perform your action
Have a look at java.awt.Desktop API for opening a link using the default browser (this API is available only from Java6).
artknish
2009-02-09 11:05:43
+3
A:
You can do this using a JLabel, but an alternative would be to style a JButton. That way, you don't have to worry about accessibility and can just fire events using an ActionListener.
public class Link {
public static void main(String[] args) throws URISyntaxException {
final URI uri = new URI("http://java.sun.com");
JFrame frame = new JFrame("Links");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(100, 400);
Container container = frame.getContentPane();
container.setLayout(new GridBagLayout());
// JButton
JButton button = new JButton();
button
.setText("<HTML>Click the <FONT color=\"#000099\"><U>link</U></FONT> to go to the Java website.</HTML>");
button.setHorizontalAlignment(SwingConstants.LEFT);
button.setBorderPainted(false);
button.setOpaque(false);
button.setBackground(Color.WHITE);
button.setToolTipText(uri.toString());
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
open(uri);
}
});
container.add(button);
frame.setVisible(true);
}
private static void open(URI uri) {
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(uri);
} catch (IOException e) {
// TODO: error handling
}
} else {
// TODO: error handling
}
}
}
McDowell
2009-02-09 12:03:05