[英]How can i make System.in read from a JTextField
I am trying to make System.in InputStream read from a JTextField. 我正在尝试从JTextField中读取System.in InputStream。
What i need it to do, is to allow .read()
to proceed once a user presses enter in a JTextField with a String in it. 我需要做的是,一旦用户在JTextField中输入一个包含String的字符串,就允许
.read()
继续。
The issue is that I don't know when .read() will be invoked, and i want it to block without freezing the main thread, until enter is pressed by the user in the JTextField where it will notify the thread waiting. 问题是我不知道什么时候会调用.read(),并且我希望它在不冻结主线程的情况下阻塞,直到用户在JTextField中按下Enter键,它将通知线程等待。
So far i tried the following: 到目前为止我尝试了以下内容:
public class InputStreamHandlerThread extends Thread {
private JTextField txt;
public InputStreamHandlerThread(JTextField txt) {
this.txt = txt;
start();
}
@Override
public void run() {
System.setIn(new FakeInputStream());
}
class FakeInputStream extends InputStream {
private int indx = 0;
@Override
public int read() throws IOException {
if (indx == txt.getText().length()) {
indx = 0;
try {
synchronized (this) {
wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
int byt = txt.getText().getBytes()[indx];
indx++;
return byt;
}
}
}
which is initialized and started by the GUI thread. 由GUI线程初始化并启动。 So once the GUI loads, it creates an instance of this class and keeps a pointer so that when the enter key is pressed on the keyboard within the JTextField, it is notified to read from it.
因此,一旦GUI加载,它就会创建一个这个类的实例并保留一个指针,这样当在JTextField中的键盘上按下回车键时,它会被通知从它读取。
in = new JTextField();
in.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent a) {
if (a.getKeyChar() == '\n') {
inputStreamHandler.notify();
}
}
});
So currently there are three threads: 所以目前有三个主题:
1. The main thread on what the GUI runs on 1. GUI运行的主要线程
2. The InputStream handler thread (See above ^) 2. InputStream处理程序线程(见上文^)
3. The thread that reads from System.in 3.从System.in读取的线程
The problem is that once i invoke inputStreamHandler.notify();
问题是,一旦我调用
inputStreamHandler.notify();
it throws a java.lang.IllegalMonitorStateException
which according to the docs, is thrown if the thread is not the holder of the lock. 如果线程不是锁的持有者,它会抛出一个
java.lang.IllegalMonitorStateException
,它根据文档被抛出。 How do i resolve this? 我该如何解决这个问题?
Thank you :-) 谢谢 :-)
String text;
...
in.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
text = in.getText();
}
});
Make sure you make text and in both fields. 确保在两个字段中创建文本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.