Search code examples
javaswingjtextfieldblockingqueue

BlockingQueue can't read String from JTextField


I am having an issue creating a custom console, on the following code:

public class UserConsole {

    protected static BlockingQueue<String> inputData;

    private final static JTextArea textArea = new JTextArea();
    private static JTextField textField = new JTextField("");

private void createGUI() {

    final KeyListener returnAction = new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyChar() == '\n') {
                    returnInput();
                   }
            }};
    }

private void returnInput() {


//Here is the problem, the BlockingQueue throws a NullPointerException, which is strange, because the...
//...right after "System.out.println(textField.getText());" works perfectly fine.
   inputData.offer(textField.getText());
        System.setOut(userStream);
        System.out.println(textField.getText());
        textField.setText("");
        System.setOut(nebulaStream);

          }
}

I tried searching online, but didn't find anything, also tried adding .toString() but it does not work as well.

As far as I know, a BlockingQueue cannot be initialized... So my final question is. Why is the BlockingQueue not reading the JTextField's string, and how can it be solved?

I hope it is not something obvious that I missed, every help is appreciated!


Solution

  • As far as I know, a BlockingQueue cannot be initialized... So my final question is. Why is the BlockingQueue not reading the JTextField's string, and how can it be solved?

    We aren't seeing some of the important sections of the code but here are some possible problems.

    1. I don't see where the blocking queue is actually instantiated. Maybe the initialization line should be something like:

      protected static final BlockingQueue<String> inputData = new LinkedBlockingQueue<>();
      
    2. We don't see where the string is removed from the blocking queue. If you want to check to see if the result has been calculated then you should use poll() which will return null until the reset is offered to the blocking queue.

      // this will not wait for the result but will return null initially
      String jtextResult = inputData.poll();
      

      If you need to wait for the result then use take() but you should never do this on a GUI thread because your UI will pause until the result is calculated negating the need for the background thread.