Close

Java Swing - How to set caret position of a JTextComponent at a given Point?

[Last Updated: Jun 6, 2018]

Java Swing 

To set caret Position of a JTextComponent (JTextField, JTextArea, JTextPane, JEditorPane etc) at a specified Point, use following method of JTextComponent:

public int viewToModel2D(Point2D pt)

Above method is introduced in Java 9. For older versions use following method (deprecated in Java 9):

public int viewToModel(Point pt)

Example

Following snippet shows how to set caret position at mouse right click before showing a popup:

  JTextComponent tc = getTextComponent();
  tc.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
                if (e.isPopupTrigger()) {
                    int rightClickCaretPosition = tc.viewToModel2D(e.getPoint());
                    tc.setCaretPosition(rightClickCaretPosition);
                     .....
                }
            }
        });

See Also