Just use a caret listener sort of like this:
private int lastLength;
public void caretUpdate(CaretEvent e)
{
String currentText = textArea.getText();
//Make sure that the user typed something (the size of the text are changed)
//before we do anything. Don't bother when they only select around.
if (currentText.length() != lastLength)
{
lastLength = currentText.length();
//See if the last character is a newline.
if (currentText.charAt(currentText.length()-1) == '\n')
{
//Check commands, blah blah.
//Add our response to the box.
String responseString = "COMMAND EXECUTED.\n";
//Match the new size that we will have when the response is added.
lastLength += responseString.length();
//The VERY IMPORTANT thing to note here is that this will immediately
//call caretUpdate again! That is why changing the length first is important.
lastLength.setText(lastLength.getText() + responseString);
}
}
}
I just typed that now, but I have dealt with caretListener before, and it’s certainly a mixed bag. On the one hand it works quite well, on the other it can’t detect the difference between the user typing directly and you adding in your own stuff. What I put above should probably be an acceptable solution, but other ways of doing it are using textArea.setEditable(false) while you are adding text in, then set setEditable(true) once you’ve finished. The problem with this is that it grays out the text and removes and selections (which may be just fine for your purposes). You can keep the text from graying if you call textArea.setDisabledTextColor(myNormalTextColor).
I’ve done a lot of dynamic text field / text area editing in various apps, and CaretListener seemed to be the best bet. One example I used this for was to fill in keywords as the user typed, and select the extra letters so they could delete it as they went. You know, the usual way of suggesting keywords. It was a surprising pain in the butt to get it working nicely. Another example is having the value in the text box saved every time its value changes. This causes more problems because you either do it with every caret change (which can cause a lot of problems when the user has put in improper input and you want to warn them), or when any character changes - which means storing not just a length but also a string that must be compared with every letter type.
Either way, it’ll take some work, but you can make it work for you.
Oh yeah, and to get this working you need to do this:
public class MyClass implements CaretListener
{
public MyClass()
{
textArea = new JTextArea(/*blah blah*/);
textArea.addCaretListener(this);
}
//This must be implemented in order to allow this to be a caret listener.
public void caretUpdate(CaretEvent e)
{
//code from above
}
}