如何确定JavaFX中TextArea中单击的字符的索引?

时间:2015-06-02 10:51:25

标签: java javafx textarea mouseevent

我想为TextArea编写一个事件处理程序,在用户单击TextArea时可以确定单击的字符的索引并根据此行为进行操作。

Get cursor position (in characters) within a text Input field中建议的解决方案是Javascript而不是Java,并且不回答如何将鼠标点击坐标转换为文本索引。

目前我有:

private EventHandler<MouseEvent> mouseHandler = new EventHandler<MouseEvent>() {

        @Override
        public void handle(MouseEvent mouseEvent) {

            int x=(int)mouseEvent.getX();
            int y=(int)mouseEvent.getY();

            String type=mouseEvent.getEventType().toString();

            if(type=="MOUSE_CLICKED")
            {
                System.out.println("Mouse clicked over textarea at x="+x+" y="+y);

                // TODO

                // determine text index under click
            }
        }
    };
TextArea my_textarea=new TextArea();
my_textarea.setOnMouseClicked(mouseHandler);

1 个答案:

答案 0 :(得分:0)

我的解决方案:

import groovy.json.JsonSlurper
import groovy.util.ConfigSlurper

def response = '''{
   "path" : {
         "field" : "My Wanted Value"
    }
}'''

// get the properties from the config file
def urlFile = new File('C:/temp/myProps.txt').toURI().toURL()
def config = new ConfigSlurper().parse(urlFile);
def path=config.path
def value=config.value

def json = new JsonSlurper().parseText response

// split the path an iterate over it step by step
// to find your value
path.split("\\.").each {
 json = json[it]
}

assert json == value

println json // My Wanted Value
println value // My Wanted Value

...

 private EventHandler<MouseEvent> mouseHandler = new EventHandler<MouseEvent>() {

        @Override
        public void handle(MouseEvent mouseEvent) {

            int x=(int)mouseEvent.getX();
            int y=(int)mouseEvent.getY();

            String type=mouseEvent.getEventType().toString();

            if(type.equals("MOUSE_CLICKED"))
            {
                System.out.println("Mouse clicked over textarea at x="+x+" y="+y);

                System.out.println("Caret position: "+my_textarea.getCaretPosition());
            }

        }

    };