设置System.in以从JTextField读取 [英] Setting System.in to read from JTextField
本文介绍了设置System.in以从JTextField读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找如何将System.in
替换为直接从JTextField
读取的InputStream
的方向.
I'm looking for direction on how to replace System.in
with an InputStream
that reads directly from a JTextField
.
到目前为止,我的方法几乎是反复试验.我目前有
So far my approach has pretty much been trial and error. I currently have;
JTextField input = new JTextField();
System.setIn(new InputStream() {
int ptr = 0;
@Override
public int read() throws IOException {
int c;
try {
c = input.getText().charAt(ptr);
}
catch (IndexOutOfBoundsException ioob) {
return 0;
}
ptr++;
return c;
}
});
这会产生一个NoSuchElementException
,就像在输入为空并且我认为永远找不到分隔符时尝试读取一样.
This yields an NoSuchElementException
as in attempts to read when the input is empty and I assume can never find a delimiter.
我错过了什么方法?
推荐答案
好吧,这是我用来使其正常工作的方法.如果有人可以改善此答案,请放心.
Well, this is the method that I used to get it working correctly. If anyone can improve this answer then feel free.
final LinkedBlockingQueue<Character> sb = new LinkedBlockingQueue<Character>();
final JTextField t = new JTextField();
t.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
sb.offer(e.getKeyChar());
}
...
});
System.setIn(new BufferedInputStream(new InputStream() {
@Override
public int read() throws IOException {
int c = -1;
try {
c = sb.take();
} catch(InterruptedException ie) {
}
return c;
}
}));
这篇关于设置System.in以从JTextField读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文