来自jTextPane的可点击文本 [英] clickable text from jTextPane

查看:93
本文介绍了来自jTextPane的可点击文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现将文本设置为jTextPane的功能.因此,当用户单击jTextPane中的某个单词时,该单词的定义应显示在jTextArea中.我知道如何在jTextPanejTextArea中显示文本.令我困扰的是,当我单击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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆