这个实现怎么样
import java.io.IOException;
import java.io.InputStream;
import javax.swing.JTextField;
public class JTextFieldInputStream extends InputStream {
byte[] contents;
int pointer = 0;
public JTextFieldInputStream(final JTextField text) {
text.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
if(e.getKeyChar()=='\n'){
contents = text.getText().getBytes();
pointer = 0;
text.setText("");
}
super.keyReleased(e);
}
});
}
@Override
public int read() throws IOException {
if(pointer >= contents.length) return -1;
return this.contents[pointer++];
}
}
要使用此输入流,请执行以下操作
InputStream in = new JTextFieldInputStream( someTextField );
char c;
while( (c = in.read()) != -1){
//do whatever with c
}
只有当我点击进入时它才会读取?
in.read()
如果返回值-1
意味着流的结束,它会在您调用时读取
(我是否能够进行修改以使 Enter 键清空 JTextField?)
您需要添加一个动作侦听器,此功能与输入流的工作无关