【发布时间】:2015-12-14 09:36:52
【问题描述】:
我在寻找在JFrame 中添加滚动条的方法时遇到了一些问题。我找到了一种将System.{in,out,err} 重定向到JTextArea 的方法,但我没有成功添加滚动条。我希望这个问题不是多余的。
public class console extends JTextArea {
public static JTextArea console(final InputStream out, final PrintWriter in) {
final JTextArea area = new JTextArea();
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();
area.addKeyListener(new KeyAdapter() {
private StringBuffer line = new StringBuffer();
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;
}
public static void main(String[] args) throws IOException {
PipedInputStream inPipe = new PipedInputStream();
PipedInputStream outPipe = new PipedInputStream();
System.setIn(inPipe);
System.setOut(new PrintStream(new PipedOutputStream(outPipe), true));
PrintWriter inWriter = new PrintWriter(new PipedOutputStream(inPipe), true);
JFrame frame = new JFrame("\"Console\"");
frame.getContentPane().add(console(outPipe, inWriter));
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
// my code
}
【问题讨论】:
-
不要使用
KeyListener(通常,但尤其是)文本组件。相反,我们结合了DocumentListener和键绑定。看看Implementing a Document Filter 和How to Use Key Bindings
标签: java swing jtextarea swingworker