我最近尝试了同样的事情,这是我的代码:
class TexfFieldStreamer extends InputStream implements ActionListener { private JTextField tf; private String str = null; private int pos = 0; public TexfFieldStreamer(JTextField jtf) { tf = jtf; } //gets triggered everytime that "Enter" is pressed on the textfield @Override public void actionPerformed(ActionEvent e) { str = tf.getText() + "n"; pos = 0; tf.setText(""); synchronized (this) { //maybe this should only notify() as multiple threads may //be waiting for input and they would now race for input this.notifyAll(); } } @Override public int read() { //test if the available input has reached its end //and the EOS should be returned if(str != null && pos == str.length()){ str =null; //this is supposed to return -1 on "end of stream" //but I'm having a hard time locating the constant return java.io.StreamTokenizer.TT_EOF; } //no input available, block until more is available because that's //the behavior specified in the Javadocs while (str == null || pos >= str.length()) { try { //according to the docs read() should block until new input is available synchronized (this) { this.wait(); } } catch (InterruptedException ex) { ex.printStackTrace(); } } //read an additional character, return it and increment the index return str.charAt(pos++); }}并像这样使用它:
JTextField tf = new JTextField(); TextFieldStreamer ts = new TextFieldStreamer(tf); //maybe this next line should be done in the TextFieldStreamer ctor //but that would cause a "leak a this from the ctor" warning tf.addActionListener(ts); System.setIn(ts);
自从我编写Java以来已经有一段时间了,所以我可能不了解最新的模式。您可能还应该重载,
intavailable()但是我的示例仅包含使它与
BufferedReaders
readLine()函数一起工作的最低要求。
编辑: 为了使它起作用,
JTextField您必须使用
implements KeyListener而不是,
implementsActionListener然后
addKeyListener(...)在textarea上使用。您需要代替的功能
actionPerformed(...)是
publicvoid keyPressed(KeyEvent e),然后您必须进行测试,
if (e.getKeyCode() ==e.VK_ENTER)而不是使用整个文本,而只需使用游标前最后一行的子字符串即可,
//ignores the special case of an empty line//so a test for n before the Caret or the Caret still being at 0 is necessaryint endpos = tf.getCaret().getMark();int startpos = tf.getText().substring(0, endpos-1).lastIndexOf('n')+1;输入字符串。因为否则,您每次按Enter时都将读取整个textarea。



