0

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.

CalvT
  • 3,123
  • 6
  • 37
  • 54
NoNaMe
  • 6,020
  • 30
  • 82
  • 110

2 Answers2

4

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
            }
        }
    });
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Alex Coleman
  • 7,216
  • 1
  • 22
  • 31
1

Usually when we want a label to be clickable, we just make it a button. I did recently use a Label instead of a button because I found it easier to control the appearance (no border around the icon) and I wanted the label to look different depending on some data that the application is showing. But I probably could have just done the whole thing with a JButton anyway.

If you want only part of your JLabel to be clickable, that gets more complicated. You would need to check the relative mouse coordinates when the mouse is clicked to see if it corresponds to the part of your label that you want to be clickable.

Alternatively, you might want to look at JEditorPane instead. This lets you place HTML into a swing app and then you can probably implement some HyperLinkListener.

But if you do need a label to fire an action, as you originally requested, you can add a mouselistener to it like this:

noteLabel = new JLabel("click me");
noteLabel.addMouseListener( new MouseAdapter() {
    public void mousePressed(MouseEvent e) {
        System.out.println("Do something");
    }

    public void mouseEntered(MouseEvent e) {
        //You can change the appearance here to show a hover state
    }

    public void mouseExited(MouseEvent e) {
        //Then change the appearance back to normal.
    }
});
Rob
  • 4,927
  • 12
  • 49
  • 54
Thorn
  • 4,015
  • 4
  • 23
  • 42