readLine on System.in,而不挂起 Swing GUI 线程



我有以下代码应该将 System.in 重定向到 JTextField。但是每当我尝试new BufferedReader(new InputStreamReader(System.in)).readLine();时,Swing GUI 都会挂起。如何在不挂起 GUI 线程的情况下从 System.in 读取行?

private static LinkedBlockingQueue<Character> sb = new LinkedBlockingQueue<Character>();
BufferedInputStream s = new BufferedInputStream(new InputStream() {
    int c = -1;
    @Override
    public int read() throws IOException {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    c = sb.take();
                } catch (InterruptedException ie) {
                    ie.printStackTrace();
                }
            }
        });
        thread.start();
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return c;
    }
});
JTextField t = new JTextField();
    t.addKeyListener(new KeyListener() {
        @Override
        public void keyTyped(final KeyEvent e) {
            sb.offer(e.getKeyChar());
            if (e.getKeyChar() == 'n' || e.getKeyChar() == 'r') {
                t.setText("");
            }
        }
        @Override
        public void keyPressed(KeyEvent arg0) {
        }
        @Override
        public void keyReleased(KeyEvent arg0) {
        }
    });
System.setIn(s);

定义一个回调类,这里,我用了一个接口,你可以跳过这个阶段。

interface Callback {
    void updateText(String s);
}
public class  CallbackImpl implements Callback  {// implements this interface so that the caller can call text.setText(s) to update the text field.
    JTextField text;// This is the filed where you need to update on.
    CallbackImpl(JTextField text){//we need to find a way for CallbackImpl to get access to the JTextFiled instance, say pass the instance in the constructor, this is a way.
     this.text=text;
    }
    void updateText(String s){
         text.setText(s);//updated the text field, this will be call after getting the result from console.
    } 
}

定义一个执行作业的线程,并在作业(从控制台读取)完成后调用回调方法。

class MyRunable implements Runnable {
    Callback c; // need a callable instance to update the text filed
    public MyRunable(Callback c) {// pass the callback when init your thread
        this.c = c;
    }
    public void run() {
        String s=// some work reading from System.in
        this.c.updateText(s); // after everything is done, call the callback method to update the text to the JTextField.
    }
}

要使其正常工作,请在侦听器处启动此线程:

new Thread(new MyRunable(new CallbackImpl(yourJtextFiled))).start();//start another thread to get the input from console and update it to the text field.

最新更新