CIT 594, Additional Help with the Animals! Assignment
Spring 2002, David Matuszek

If you are having trouble with co-ordinating input/output from the Animals! program, here are a couple of methods that you can use that should help. While these methods are not strictly necessary, using them can avoid dealing with some timing issues.

There are two methods, String waitForInput(), which waits for input from a TextField and, when the user provides that input, returns with the String that the user entered. The other method, void provideInput(String), gives the first method the input that it is waiting for. waitForInput() can be called wherever you want input from a text field; provideInput(String) should be called only from within the event handler for that field.

In addition, there are two global variables, boolean available and String inputText, that are used by these two methods. These must be provided, but can be ignored; just use the methods mentioned above.

Here's the code:

    public boolean available = false;
    public String inputText;
    
    public synchronized String waitForInput() {
        while (! available) {
            try { wait(); }
            catch (InterruptedException e) {}
        }
        available = false;
        notifyAll();
        return inputText;
    }
    
    public synchronized void provideInput(String theInput) {
        while (available) {
            try { wait(); }
            catch (InterruptedException e) {}
        }
        inputText = theInput;
        available = true;
        notifyAll();
    }

Here's an example of using the code from within an event handler:

    private void textField2ActionPerformed(ActionEvent evt) {
        String input = textField2.getText();
        provideInput(input);
    }

Finally, here's a complete sample program for testing the above code, which you are welcome to compile and try out if you want to see these methods in action.