【发布时间】:2012-03-13 08:07:12
【问题描述】:
我想要一个可以完全工作的 JTextArea 而不是 控制台,但我不知道该怎么做!
谢谢
【问题讨论】:
-
很可能是因为您的问题没有显示出您自己解决问题的任何努力。
标签: java swing console system jtextarea
我想要一个可以完全工作的 JTextArea 而不是 控制台,但我不知道该怎么做!
谢谢
【问题讨论】:
标签: java swing console system jtextarea
解决问题的方法是将System.{in,out,err} 重定向到JTextArea。
从System.out 开始,使用System.setOut 方法将其重定向到您的JTextArea 组件非常简单。在下面的示例中,我使用管道和SwingWorker 完成了此操作,但这都是花哨的东西,实际上使输出对摆动组件更简单。
模拟System.in 是类似的,您需要使用System.setIn 将击键重定向到System.in。同样,在下面的示例中,我使用管道来获得更好的界面。我还缓冲该行(就像“普通”控制台一样),直到您按下回车键。 (请注意,例如,箭头键不起作用,但让它也被处理/忽略不应该做太多工作。)
下面屏幕截图中的文本是通过多次调用“正常”System.out.print.. 方法然后使用Scanner 等待System.in 上的输入产生的:
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");
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;
}
还有main方法的例子:
public static void main(String[] args) throws IOException {
// 1. create the pipes
PipedInputStream inPipe = new PipedInputStream();
PipedInputStream outPipe = new PipedInputStream();
// 2. set the System.in and System.out streams
System.setIn(inPipe);
System.setOut(new PrintStream(new PipedOutputStream(outPipe), true));
PrintWriter inWriter = new PrintWriter(new PipedOutputStream(inPipe), true);
// 3. create the gui
JFrame frame = new JFrame("\"Console\"");
frame.add(console(outPipe, inWriter));
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
// 4. write some output (to JTextArea)
System.out.println("Hello World!");
System.out.println("Test");
System.out.println("Test");
System.out.println("Test");
// 5. get some input (from JTextArea)
Scanner s = new Scanner(System.in);
System.out.printf("got from input: \"%s\"%n", s.nextLine());
}
【讨论】:
【讨论】: