我有以下代码,应该将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);
答案 0 :(得分:2)
定义一个Callback类,在这里,我使用一个接口,你可以跳过这个阶段。
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.