我有一个 JFrame,其中包含一个 JPanel,其中包含一个 JTextArea。我已经成功地将 System.out 指向 JTextArea,但是当我尝试使用 Scanner(System.in) 来解析来自 JTextArea 的输入时,它甚至似乎没有加载任何内容。例如,当我构建和运行应用程序时,什么也没有发生,也没有显示任何框架。这是我的代码:
/**
* Create the frame.
*/
public TerminalForm() {
setTitle("Terminal");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 570, 370);
contentPane = new JPanel();
contentPane.setBorder(BorderFactory.createEmptyBorder());
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
PipedInputStream inPipe = new PipedInputStream();
PipedInputStream outPipe = new PipedInputStream();
System.setIn(inPipe);
try {
System.setOut(new PrintStream(new PipedOutputStream(outPipe), true));
} catch (IOException e1) {
e1.printStackTrace();
}
PrintWriter inWriter = null;
try {
inWriter = new PrintWriter(new PipedOutputStream(inPipe), true);
} catch (IOException e) {
e.printStackTrace();
}
final JTextArea txtIO = console(outPipe, inWriter);
txtIO.setFont(new Font("Andale Mono", Font.PLAIN, 12));
txtIO.setCaretColor(new Color(50, 205, 50));
txtIO.getCaret().setVisible(true);
txtIO.getCaret().setSelectionVisible(true);
txtIO.setLineWrap(true);
txtIO.setForeground(new Color(50, 205, 50));
txtIO.setBackground(new Color(0, 0, 0));
txtIO.setBorder(BorderFactory.createEmptyBorder());
contentPane.add(txtIO);
// 5. get some input (from JTextArea)
Scanner s = new Scanner(System.in);
System.out.printf("got from input: \"%s\"%n", s.nextLine());
}
public static JTextArea console(final InputStream out, final PrintWriter in) {
final JTextArea area = new JTextArea();
// handle "System.out"
new SwingWorker<Void, String>() {
@Override protected Void doInBackground() throws Exception {
Scanner s = new Scanner(out);
while (s.hasNextLine()) publish(s.nextLine() + "\n");
s.close();
return null;
}
@Override protected void process(List<String> chunks) {
for (String line : chunks) area.append(line);
}
}.execute();
// handle "System.in"
area.addKeyListener(new KeyAdapter() {
private StringBuffer line = new StringBuffer();
@Override public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if (c == KeyEvent.VK_ENTER) {
in.println(line);
line.setLength(0);
} else if (c == KeyEvent.VK_BACK_SPACE) {
line.setLength(line.length() - 1);
} else if (!Character.isISOControl(c)) {
line.append(e.getKeyChar());
}
}
});
return area;
}