My goal is to make anyGivenWord in a JTextArea "actionable". For example, when you hover the mouse over anyGivenWord, a tooltip appears, but not when you hover the mouse over any other word in the JTextArea. Since you can't do this directly to my knowledge, I was thinking of placing a component over where every anyGivenWord appears in the JTextArea, and have it re-position itself when the JTextArea's size changes, so that clicking on what appears to be anyGivenWord is actually clicking on the component(resulting in some listener being triggered). To do this, I would need to know at what point(x,y) that word occurs, so I can place the component at that point.
I was thinking I could search through the JTextArea and select instances of anyGivenWord, and then getSelectionStart() and getSelectionEnd(), but I think the int those methods return is the index of the first/last letter selected, as in, its position in the string returned by getText(). What I need is the x/y coordinates. Is this possible?
If not...any suggestions for more elegant ways to do what I'm trying to do?
You can use a JEditorPane with HTML and add Hyperlinks to any given word. Read the section from the Swing tutorial on How to Use Editor Panes for the basics to get you started.
You can then add a HyperlinkListener
to respond to events when the word is clicked. Read the JEditorPane
API for an example of using a HyperlinkListener
.
For example, when you hover the mouse over anyGivenWord, a tooltip appears,
If you don't want to use Hyperlinks then you could control the tooltip text by overriding the getToolTipText(...)
method. This method receives the MouseEvent so you can get the mouse location. You can then use the viewToModel(...)
method of the JTextArea to get the offset of the mouse into the Document. Then check out the Utilities
. class which will help you get the start/end offsets of the word so you can use the getText(...)
method to extract the word at the current mouse location.