BlockingQueue 无法从 JTextField 读取字符串

BlockingQueue can't read String from JTextField

我在使用以下代码创建自定义控制台时遇到问题:

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

          }
}

我尝试在线搜索,但没有找到任何东西,也尝试添加 .toString() 但它也不起作用。

据我所知,BlockingQueue 无法初始化...所以我的最后一个问题是。 为什么 BlockingQueue 不读取 JTextField 的字符串,如何解决?

我希望我没有遗漏任何明显的东西,感谢您的帮助!

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?

我们没有看到代码的一些重要部分,但这里有一些可能的问题。

  1. 我没有看到阻塞队列实际实例化的位置。也许初始化行应该是这样的:

    protected static final BlockingQueue<String> inputData = new LinkedBlockingQueue<>();
    
  2. 我们没有看到从阻塞队列中删除字符串的位置。如果你想检查结果是否已经计算出来,那么你应该使用 poll() 它将 return null 直到重置被提供给阻塞队列。

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

    如果你需要等待结果然后使用take()但是你不应该在GUI线程上这样做因为你的UI 将暂停,直到计算结果否定后台线程的需要。