[英]readLine on System.in without hanging the Swing GUI thread
我有以下代碼,應該將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);
定義一個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.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.