Search code examples
javaswingjeditorpanejwindow

Finding the X and Y coordinates of end of text in JeditorPane


I've created a popup list as an autocomplete feature in text editor project i'm working on, and i'm facing an issue with setting the location of this pop list at the point the text are typed in the JeditorPane component

here is my code(right now the list open on the bottom of the frame):

    private void showPopUpWindow() {
    autoSuggestionPopUpWindow.getContentPane().add(suggestionsPanel);
    autoSuggestionPopUpWindow.setMinimumSize(new Dimension(textField.getWidth(), 30));
    autoSuggestionPopUpWindow.setSize(tW, tH);
    autoSuggestionPopUpWindow.setVisible(true);

    int windowX =0;
    int windowY =0;

    windowX = container.getX() + textField.getX() + 5;
    if (suggestionsPanel.getHeight() > autoSuggestionPopUpWindow.getMinimumSize().height) {
        windowY = container.getY() + textField.getY() + textField.getHeight() + autoSuggestionPopUpWindow.getMinimumSize().height;
    } else {
        windowY = container.getY() + textField.getY() + textField.getHeight() + autoSuggestionPopUpWindow.getHeight();
    }


    autoSuggestionPopUpWindow.setLocation(windowX, windowY);
    autoSuggestionPopUpWindow.setMinimumSize(new Dimension(textField.getWidth(), 30));
    autoSuggestionPopUpWindow.revalidate();
    autoSuggestionPopUpWindow.repaint();

}

the object "autoSuggestionPopUpWindow" is a instance of JWindow class

how can i find this point?


Solution

  • Don't use a JEditorPane. A JEditorPane is best used to display simple HTML.

    Instead I would suggest you use a JTextPane for formatted text or a JTextArea for plain text.

    You can display the popup based on the location of the caret:

    int offset = textComponent.getCaretPostion();
    

    Then you get the Rectangle that represents the location of the caret in the text component:

    Rectangle location = textComponent.modelToView(offset);
    

    Then you can set the location of the window based on the rectangle:

    window.setLocation(location.x, location.y + location.height);