JavaTechnical
JavaTechnical

Reputation: 9357

Display JDialog below caret position

I would like to display JDialog below the current caret position in JTextArea in my program. I tried using, modelToView() to get the caret position but when i use the setLocation() method of the JDialog in this way, I am unable to get the desired location.

Rectangle r=jTextArea.modelToView(jTextArea.getCaretPosition());
jDialog.setLocation(r.x,r.y+jTextArea.getFontMetrics(jTextArea.getFont()).getHeight());

Also, could any one tell me why this snippet is not working in the desired way?

Upvotes: 1

Views: 81

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347334

The rectangle is likely relative to the parent component. You need to translate the location to the screen

SwingUtilities.convertPointToScreen(r.getLocation(), jTextArea);
jDialog.setLocation(pos.x,pos.y+jTextArea.getFontMetrics(jTextArea.getFont()).getHeight());

I've not tried this, but I think...

jDialog.setLocation(pos.x,pos.y+r.height);

Might be cleaner...?

Upvotes: 2

Related Questions