目前,我正在试图解决一个问题,我需要找到基于鼠标点击的地方在一个JEditorPane一段文本的位置。

基本上,当用户右击了一个字,我需要找出这个词是什么。要做到这一点,我需要找出在用户点击文本哪个位置。我知道我可以很容易地从被传递到方法的mousePressed中的MouseEvent鼠标的位置,并且有人告诉我,你可以将它转换为获得在一段文本字符索引 - 但是我想不出怎么办此

我曾尝试viewToModel()方法JEditorPane中但是这所以无论是我用错了,或不以这种方式工作是给我回的文本错误的位置。

任何想法?

有帮助吗?

解决方案

Invoking viewToModel() is the correct way to do this:

public void mouseClicked(MouseEvent e) {
    JEditorPane editor = (JEditorPane) e.getSource();
    Point pt = new Point(e.getX(), e.getY());
    int pos = editor.viewToModel(pt);
    // whatever you need to do here
}

其他提示

I've solved this problem on my own. It turns out viewToModel() is exactly what I should be using here, the problem was that I was passing in the wrong Point to it.

From the MouseEvent, I was using the getLocationOnScreen() method to work out the point when in fact I should have been using the getPoint() method.

Thanks to anyone who read this question.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top