I am implementing a function which sets text to jTextPane
. So when user clicks certain word in jTextPane
, the definition of that word should be displayed in jTextArea
. I know how to display text in jTextPane
and in jTextArea
. What's troubling me is that when I click in jTextPane
the whole text is getting selected instead of selecting that particular word :'( . I have done some research on caret positions and all but I can't quite get it. This is as far as I got:
private void jTextPane1MouseClicked(java.awt.event.MouseEvent evt) {
try
{
StyledDocument doc=(StyledDocument) jTextPane1.getDocument();;
Element ele = doc.getCharacterElement(jTextPane1.viewToModel(evt.getPoint()));
AttributeSet as = ele.getAttributes();
/* Here after getting the word from jTextPane we print the definition
of that word in jTextArea... I got the code for this part */
}
}
How can I get only the clicked word??
You can use
viewToModel()
method (in fact you already use it) to detect charatcer position for the clicked point.Then use
javax.swing.text.Utilities
class. It has methods:Just pass the position obtained from
viewToModel()
call and get start and end positions for the clicked word. Then you can select it by setSelectionStart()/setSelectionEnd() calls passing the word start/end offsets.