Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possibly to create selectable hyperlink with basic Swing components in Java?

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.

like image 615
Oleg Kuznetsov Avatar asked Apr 08 '11 21:04

Oleg Kuznetsov


2 Answers

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);
                }
            }
        }
    });
like image 165
Michael Borgwardt Avatar answered Sep 23 '22 22:09

Michael Borgwardt


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);  
        }  
   }  
  });  
like image 21
javing Avatar answered Sep 23 '22 22:09

javing