Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Finding word clicked on in JTextArea

49 views
Skip to first unread message

Fred

unread,
Dec 8, 2008, 5:55:30 PM12/8/08
to
I have a JTextArea (uneditable) inside a JScrollPane
When the user clicks somewhere in the JTextArea, I want to find the
word containing the mouse event.

Can this be done simply, or does one have to go through all the hoops
of getting the viewport, getting the view position, add the event
position
to the view position, get the document, get the text starting at the
position (hmmm - what length to get...), parse it , etc ?
--
Fred

Daniel Pitts

unread,
Dec 8, 2008, 6:31:18 PM12/8/08
to

Fred

unread,
Dec 8, 2008, 6:48:19 PM12/8/08
to
On Dec 8, 3:31 pm, Daniel Pitts

<newsgroup.spamfil...@virtualinfinity.net> wrote:
> Fred wrote:
> > I have a JTextArea (uneditable) inside a JScrollPane
> > When the user clicks somewhere in the JTextArea, I want to find the
> > word containing the mouse event.
>
> > Can this be done simply, or does one have to go through all the hoops
> > of getting the viewport, getting the view position, add the event
> > position
> > to the view position, get the document, get the text starting at the
> > position (hmmm - what length to get...), parse it , etc ?
> > --
> > Fred
>
> You could try
> CaretListener:http://java.sun.com/javase/6/docs/api/javax/swing/event/CaretListener...
>

Actually I am clicking with the right mouse button - I do not wish to
change
the caret position.
--
Fred

Sigfried

unread,
Dec 9, 2008, 6:39:59 AM12/9/08
to
Fred a écrit :

from
http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/text/JTextComponent.html
you can use viewToModel(java.awt.Point)

Fred

unread,
Dec 9, 2008, 11:03:36 AM12/9/08
to
> fromhttp://java.sun.com/j2se/1.4.2/docs/api/javax/swing/text/JTextCompone...
> you can use viewToModel(java.awt.Point)- Hide quoted text -
>
> - Show quoted text -

Thanks, Sigfried.
Here's a solution to getting the text of the line containing
the point clicked in:

int ipos = textarea.viewToModel( e.getPoint );
PlainDocument pd = (PlainDocument)textarea.getDocument();
Element elem = pd.getParagraphElement(ipos);
int ichar1 = elem.getStartOffset();
int ichar2 = elem.getEndOffset();
String line = textarea.getText( ichar1, (ichar2-ichar1+1) );

--
Fred K

Fred

unread,
Dec 9, 2008, 11:22:52 AM12/9/08
to
oops -

String line = textarea.getText( ichar1, (ichar2-ichar1-1) );
--
Fred K

0 new messages