 |
AppletTalk.com Java discussions newsgroups
|
| View previous topic :: View next topic |
| Author |
Message |
eNc^ Guest
|
Posted: Wed Jun 14, 2006 3:52 am Post subject: Text Selection |
|
|
Hi i'm trying to make a button's action method perform a 'delete' on
some text in a JTextArea(). The idea is that I do this
textArea.setText(textArea.getText(0,textArea.getSelectionStart) + "" +
textArea.getText(textArea.getSelectionEnd,textArea.getDocument.getLength());
Basically if the user has seleted text in a paragraph, and the user
pushes this button (delete). The function will then remove the selected
text from the document.
The code which (above) has been shown by me doesn't work (gives
outOfBoundsException)and I would like to know if there is a way to
remove selected text from a JTextArea on the push of the button. |
|
| Back to top |
|
 |
Atif Guest
|
Posted: Wed Jun 14, 2006 7:10 am Post subject: Re: Text Selection |
|
|
eNc^ wrote:
| Quote: | Hi i'm trying to make a button's action method perform a 'delete' on
some text in a JTextArea(). The idea is that I do this
textArea.setText(textArea.getText(0,textArea.getSelectionStart) + "" +
textArea.getText(textArea.getSelectionEnd,textArea.getDocument.getLength());
Basically if the user has seleted text in a paragraph, and the user
pushes this button (delete). The function will then remove the selected
text from the document.
The code which (above) has been shown by me doesn't work (gives
outOfBoundsException)and I would like to know if there is a way to
remove selected text from a JTextArea on the push of the button.
|
took me a while to figure out, next time post a small code snippet to
work off!
remember it's " getText(offset, LENGTH) "
textArea.getDocument.getLength() gives you the length of the ENTIRE
document. you only want the length of the string after the Selection
end. that's why you were getting out of bounds errors, because you
wanted the offset plus the length of the entire document, so that's
obviously out of bounds.
do this:
<code>
int a = textArea.getSelectionStart() ;
int b = textArea.getSelectionEnd();
int c = textArea.getDocument().getLength();
String beforeS = textArea.getText(0,a ) ;
String afterS = textArea.getText(b,c-b );
textArea.setText(null);
textArea.setText(beforeS+""+afterS);
</code>
lesson learned: read parameters carefully . 'cause it would've been
correct if the 2nd parameter was asking for the 2nd offset. |
|
| Back to top |
|
 |
eNc^ Guest
|
Posted: Thu Jun 15, 2006 3:42 am Post subject: Re: Text Selection |
|
|
Thank you so much, it worked. |
|
| Back to top |
|
 |
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
|