Waiting for input with TextArea


I want to do the following, but don’t know how:
I have a TextArea and I want to use it as a console.

TextArea console;
void doSomething(){
  String input = getInputFromConsole();

What I want is, that the method doSomething() waits
for me to press ENTER in the TextArea
and then return the text which is in the TextArea
into the String input.
How can I do that ?

AWT is event-driven. Your approach can be implemented by registering a listener with the text area which will push its contents to a blocking queue and then having the doSomething() method poll the queue, but you might want to consider whether restructuring your design to be more event-driven would be a better approach.

Have you gone through any of the official Java Tutorial series on AWT and Swing?

The JTextArea class can implement this easier. The only way I have found to do it with awt.TextArea probably isn’t that good.

	public String getInputFromConsole() {
		String[] lines = console.getText().split("\n");
		return lines[lines.length-1];

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*/);

    //This must be implemented in order to allow this to be a caret listener.
    public void caretUpdate(CaretEvent e)
        //code from above

This is a really nice way to get the user input from a TextArea
and as I only used the simple ActionListener, KeyListener etc. until now,
it’s good to know.
I also made a tool with keyword suggestion, but I didn’t need it there
because I used a thread there which checked the input every 1/25 sec.
I used the StringBuffer.reverse() method to compare the actual input to
a list of keywords.
But here the thread-approach is not a secure solution as you can see.

What I really need though is something equivalent to the Dialog function


I need something that behaves like the java.util.Scanner for the default System.in-console
with my TextArea.
Probably the easiest way to describe this is:
I want to emulate a console in my game.

For example i have a method:

TextArea console;
void enterUserData(){
  console.append("Please enter your name\n");
  String name = getInputFromConsole();
  console.append("Which type of warrior do you want to be?\n");
  console.append("(1) Assassin\n");
  console.append("(2) Archer\n");
  console.append("(3) Berserker\n");
  String type = getInputFromConsole();

I should have written this before, didn’t I ? :-\