来自jTextPane的可点击文本 [英] clickable text from jTextPane
问题描述
我正在实现将文本设置为jTextPane
的功能.因此,当用户单击jTextPane
中的某个单词时,该单词的定义应显示在jTextArea
中.我知道如何在jTextPane
和jTextArea
中显示文本.令我困扰的是,当我单击jTextPane
时,整个文本都被选中,而不是选择特定的单词:'(..知道了,据我所知:
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??
推荐答案
您可以使用viewToModel()
方法(实际上您已经在使用它)来检测单击点的字符位置.
You can use viewToModel()
method (in fact you already use it) to detect charatcer position for the clicked point.
然后使用javax.swing.text.Utilities
类.它具有以下方法:
Then use javax.swing.text.Utilities
class. It has methods:
public static final int getWordStart(JTextComponent c, int offs)
public static final int getWordEnd(JTextComponent c, int offs)
只需传递从viewToModel()
调用中获得的位置,并获取所单击单词的开始和结束位置.然后,您可以通过传递单词开始/结束偏移量的setSelectionStart()/setSelectionEnd()调用来选择它.
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.
这篇关于来自jTextPane的可点击文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!