我有一个 BufferedWriter,我用它来将字符写入 PipedInputStream。基于键盘事件。但是我正在实现一个退格处理程序,但是如果没有 unputc,我看不出有什么办法。
我几乎要退回到使用字符串来缓冲当前行。
或许,我可以改用 Canvas 做得更好。 (天哪,我多么讨厌 Java!)
public class Console extends JTextArea {
/**
*
*/
private static final long serialVersionUID = 6315506875930497268L;
private PipedInputStream stdin;
private PipedOutputStream stdout;
private PipedOutputStream stderr;
private boolean bounceKey = true;
private class Dispatcher implements Runnable {
InputStream in;
public Dispatcher(InputStream in) {
this.in = in;
}
@Override
public void run() {
Reader input = new BufferedReader(new InputStreamReader(in));
int c;
try {
try {
while ((c = input.read()) >= 0) {
append(String.valueOf((char) c));
}
} finally {
input.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public Console() throws IOException {
stdin = new PipedInputStream();
stdout = new PipedOutputStream();
stderr = new PipedOutputStream();
final Writer kbd = new BufferedWriter(new OutputStreamWriter(
new PipedOutputStream(stdin)));
new Thread(new Dispatcher(new PipedInputStream(stdout))).start();
new Thread(new Dispatcher(new PipedInputStream(stderr))).start();
addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
try {
char ch = e.getKeyChar();
kbd.write(ch);
append(String.valueOf(ch));
if(ch == '\n') kbd.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
}
@Override
public void keyPressed(KeyEvent e) {
int keycode = e.getKeyCode();
switch(keycode) {
case KeyEvent.VK_BACK_SPACE:
// Erase the last char from buffer and the screen
}
}
@Override
public void keyReleased(KeyEvent e) {
} // DONOTHING
});
setEditable(false);
setFocusable(true);
setBackground(Color.black);
setForeground(Color.lightGray);
setFont(new Font("Monospace", Font.BOLD, 12));
setLineWrap(true);
}
public OutputStream getStderr() {
return stderr;
}
public OutputStream getStdout() {
return stdout;
}
public InputStream getStdin() {
return stdin;
}
public boolean isBounceKey() {
return bounceKey;
}
public void setBounceKey(boolean bounceKey) {
this.bounceKey = bounceKey;
}
}
我是一名优秀的程序员,十分优秀!