Search code examples
javaswingjlabel

using JLabel as link to open popup


Possible Duplicate:
How to add hyperlink in JLabel

I am using "JLabel" to display a paragraph, I need to make some part of that paragraph as link that will open a new popup, kindly tell me how to do this, e.g.

this is ABC application and here is the introduction of the app:
  this is line one
  this is line two
  this is line three

Here I have to make the word "two" as a click-able link to open a popup.


Solution

  • I personally would recommend the use of a JEditorPane instead of a JPanel; it is much more useful for displaying paragraphs, and can display HTML, such as links. You can then simply call addHyperlinkListener(Some hyperlinklistener) to add a listener, which will be called upon someone clicking the link. You can just pop something up, or maybe open whatever was clicked in a real browser, its up to you.

    Here's some example code (haven't test it yet, should work):

    JEditorPane ep = new JEditorPane("text/html", "Some HTML code will go here. You can have <a href=\"do1\">links</a> in it. Or other <a href=\"do2\">links</a>.");
    ep.addHyperlinkListener(new HyperlinkListener() {
             public void hyperlinkUpdate(HyperlinkEvent arg0) {
                String data = arg0.getDescription();
                if(data.equals("do1")) {
                    //do something here
                }
                if(data.equals("do2")) {
                    //do something else here
                }
            }
        });