I am trying to add a hyperlink to a JPanel. I would like to make it's text blue (and underlined) and the link should be selectable (to copy some part of it). So I tried to use JLabel: yes, it allow to write something [awful] like this:
someLabel.setText("<html><font color=\"#0000ff\"><u>http://example.com</u></font></html>");
But unfortunately, JLabel doesn't allow to select any text. I also tried to use JTextField, but in opposite, it doesn't allow to use HTML/CSS in it's fields.
So, Is where exists any way to create a hyperlink (with proper indication) with basic Swing components, which will be allow to select [and copy] part of it, or should I try to use some 3rd party components? Thank you.
You can display HTML content in a non-editable JEditorPane
. It's selectable, and you can make the links functional via a HyperlinkListener
:
JEditorPane content = new JEditorPane();
content.setContentType("text/html");
content.setEditable(false);
content.setText("<html><a href=\"http://stackoverflow.com\">Link</a></html>"));
content.addHyperlinkListener(new HyperlinkListener() {
@Override
public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
try {
Desktop.getDesktop().browse(e.getURL().toURI());
} catch (Exception e1) {
Logger.getLogger(getClass()).error(
"Error opening link " + e.getURL(), e1);
}
}
}
});
Here how can you create a JLabel with a hyperlink ,then you can just add it to your Jpanel:
public HyperLinkLabel()
{
JPanel p = new JPanel();
final String strURL = "http://www.yahoo.com";
final JLabel label = new JLabel("<html><a href=\" " + strURL + "\"> click </a></html>");
final JEditorPane htmlPane = new JEditorPane();
p.add(label);
getContentPane().add(BorderLayout.NORTH, p);
getContentPane().add(BorderLayout.CENTER, new JScrollPane(htmlPane));
setBounds(20,200, 500,500);
label.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent me) {
label.setCursor(new Cursor(Cursor.HAND_CURSOR));
}
public void mouseExited(MouseEvent me) {
label.setCursor(Cursor.getDefaultCursor());
}
public void mouseClicked(MouseEvent me)
{
System.out.println("Clicked on Label...");
try {
htmlPane.setPage(new URL(strURL));
}
catch(Exception e) {
System.out.println(e);
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With