1

So I am working on something in Java right now where I need to display lots of JTextComponents. I need to be able to turn words in any text component into a hyperlink of sorts, specifically, when these words are clicked, some method is called. Please note, I am not looking for a REAL hyperlink, just if you click on some text, a function is called. I believe JTextPane could solve this problem using components, but I can't seem to figure it out..

Yes, this question already exists, but the other one is a duplicate, and the one it links to does NOT answer this question.

user633314
  • 45
  • 2
  • 8

2 Answers2

3

A JTextArea could work for this too.

  • You could use a MouseListener and then translate the location of the click via viewToModel(Point pt).
  • You could then use javax.swing.text.Utilities.getRowStart(textArea, offset); if you need the start of the row selected, and getRowEnd(...) for the end.
  • You could have a Map<String, SomeLink> to see if a selected word is a linking word.

For an example of this, please check my answer here.

Community
  • 1
  • 1
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • Actually, I found an easier way to do it, but I have another issue... So the solution I found was to convert the selected text into a new Component using JTextPane's insertComponent method. However, when I create a new component like this, the text associated is offset a little bit below the original line... which is quite irksome. – user633314 May 14 '13 at 22:36
3

If JEditorPane or JTextPane is a satisfactory JTextComponent, then a HyperlinkListener will be invoked to perform any desired action, as shown in this complete example.

image

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045