title: How can i make System.in read from a JTextField
body: <p>I am trying to make System.in InputStream read from a JTextField.</p>
  
  <p>What i need it to do, is to allow <code>.read()</code> to proceed once a user presses enter in a JTextField with a String in it.</p>
  
  <p>The issue is that I don't know when .read() will be invoked, and i want it to block without freezing the main thread, until enter is pressed by the user in the JTextField where it will notify the thread waiting.</p>
  
  <p>So far i tried the following:</p>
  
  <pre><code>public class InputStreamHandlerThread extends Thread {
  
      private JTextField txt;
      public InputStreamHandlerThread(JTextField txt) {
          this.txt = txt;
          start();
      }
  
      @Override
      public void run() {
          System.setIn(new FakeInputStream());
      }
  
      class FakeInputStream extends InputStream {
          private int indx = 0;
  
          @Override
          public int read() throws IOException {
              if (indx == txt.getText().length()) {
                  indx = 0;
                  try {
                      synchronized (this) {
                          wait();
                      }
                  } catch (InterruptedException e) {
                      e.printStackTrace();
                  }
              }
              int byt = txt.getText().getBytes()[indx];
              indx++;
              return byt;
  
          }
      }
  }
  </code></pre>
  
  <p>which is initialized and started by the GUI thread. 
  So once the GUI loads, it creates an instance of this class and keeps a pointer so that when the enter key is pressed on the keyboard within the JTextField, it is notified to read from it. </p>
  
  <pre><code>       in = new JTextField();
         in.addKeyListener(new KeyAdapter() {
              @Override
              public void keyTyped(KeyEvent a) {
                  if (a.getKeyChar() == '\n') {
                      inputStreamHandler.notify();
                  }
              }
          });
  </code></pre>
  
  <p>So currently there are three threads:<br>
   1. The main thread on what the GUI runs on<br>
   2. The InputStream handler thread (See above ^)<br>
   3. The thread that reads from System.in</p>
  
  <p>The problem is that once i invoke <code>inputStreamHandler.notify();</code> it throws a <code>java.lang.IllegalMonitorStateException</code> which according to the docs, is thrown if the thread is not the holder of the lock. 
  How do i resolve this?</p>
  
  <p>Thank you :-) </p>