Reading text from JTextArea in java
I hav开发者_如何学Goe a JTextArea
in my Java program... I want that if I write an asterix (*) in the JTextArea
, the output will be ATX
as a text... can someone help me please?
you can do this
if(yourTextArea.getText.contains("*"))
{
yourTextArea.setText("ATX");
}
You can add a key listener to it, so when ever a key is typed, you check to see if it is an * and if it is replace it with the ATX
Oops, misread the question.
If you want to do this constantly, then the only way is through a keyListener:
http://download.oracle.com/javase/tutorial/uiswing/events/keylistener.html
In my opinion, this would probably be pretty annoying functionality for it to change one character to 3 characters as the user types. Consider doing it when the user does some method, in which case you wouldn't need a listener.
Do you mean:
String s = YourTextArea.getText().contains("*") ? "ATX" : YourTextArea.getText();
Please clarify your question so that we can help you
It sounds like you want to capture the user's input and then determine if you want to do something with it or not depending on what it is.
First off, you will need to add an action listener to this JTextArea to listen for whatever the user types so you can determine what it is. You would do this with a KeyListener. Next you need a way of determining where the caret is positioned in the JTextArea. You would do this with a CaretListener.
Now when ever a KeyPressed event occurs, you will need to determine what the key is. If it is in fact an asterisk *
you will insert the text ATX
into the JTextArea at the current position of the caret.
You will then use something like:
textarea.insert("ATX", pos);
Where textarea
is the JTextArea object and pos
is an integer that holds the current position of the caret within the JTextArea. If you are not sure how to get the caret position read up on the CaretListener API. It has everything you will need.
Output where? Into this text area itself? So, in other words do you want to implement some kind of alias?
In this case you can add KeyListener and in its keyTyped() implement your logic: if key is * add to text area your text.
精彩评论