0

I want to write an event handler for a TextArea which upon the user clicking on the TextArea can determine the index of the character clicked and act based on this.

The suggested solutions in Get cursor position (in characters) within a text Input field are Javascript instead of Java and do not answer how to convert mouse click coordinates to a text index.

Currently I have:

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);
Community
  • 1
  • 1
javachessgui
  • 147
  • 2
  • 11

1 Answers1

0

My solution:

 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());
            }

        }

    };

...

TextArea my_textarea=new TextArea();
my_textarea.setOnMouseClicked(mouseHandler);
javachessgui
  • 147
  • 2
  • 11
  • Welcome to Stackoverflow and Java! Comparing String values with "==" operator is somewhat erroneous see [Java String comparison discussion](http://stackoverflow.com/questions/995918/java-string-comparison). Also there is no need to get the String representation of event type just do `if ( mouseEvent.getEventType() == MouseEvent.MOUSE_CLICKED )`. It is more type safer. – Uluk Biy Jun 02 '15 at 11:57
  • I always mess this up. I had several bugs because of this already but for some reason I cannot learn to use .equals(). – javachessgui Jun 02 '15 at 12:13