gpt4 book ai didi

java - 将 System.in 重定向到 swing 组件

转载 作者:行者123 更新时间:2023-11-29 08:09:21 25 4
gpt4 key购买 nike

大家好,我正在使用 Swing 和 Apache Commons 制作一个终端应用程序。我能够轻松地将 System.outSystem.err 重定向到 JTextArea 但我如何为 System.in 做到这一点 ?我需要覆盖 Inputstream 方法吗?我是否需要将 StringJTextArea 转换为字节数组,然后将其传递给 InputStream?代码示例会很好。

最佳答案

我最近尝试了同样的事情,这是我的代码:

class TexfFieldStreamer extends InputStream implements ActionListener {

private JTextField tf;
private String str = null;
private int pos = 0;

public TexfFieldStreamer(JTextField jtf) {
tf = jtf;
}

//gets triggered everytime that "Enter" is pressed on the textfield
@Override
public void actionPerformed(ActionEvent e) {
str = tf.getText() + "\n";
pos = 0;
tf.setText("");
synchronized (this) {
//maybe this should only notify() as multiple threads may
//be waiting for input and they would now race for input
this.notifyAll();
}
}

@Override
public int read() {
//test if the available input has reached its end
//and the EOS should be returned
if(str != null && pos == str.length()){
str =null;
//this is supposed to return -1 on "end of stream"
//but I'm having a hard time locating the constant
return java.io.StreamTokenizer.TT_EOF;
}
//no input available, block until more is available because that's
//the behavior specified in the Javadocs
while (str == null || pos >= str.length()) {
try {
//according to the docs read() should block until new input is available
synchronized (this) {
this.wait();
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
//read an additional character, return it and increment the index
return str.charAt(pos++);
}
}

并像这样使用它:

    JTextField tf = new JTextField();
TextFieldStreamer ts = new TextFieldStreamer(tf);
//maybe this next line should be done in the TextFieldStreamer ctor
//but that would cause a "leak a this from the ctor" warning
tf.addActionListener(ts);

System.setIn(ts);

我已经有一段时间没有编写 Java 代码了,所以我可能不是最新的模式。您可能还应该重载 int available() 但我的示例仅包含使其与 BufferedReaderreadLine() 一起工作的最低限度功能。

编辑:要使其适用于 JTextField,您必须使用 implements KeyListener 而不是 implements ActionListener然后在您的 TextArea 上使用 addKeyListener(...)。您需要的函数而不是 actionPerformed(...)public void keyPressed(KeyEvent e) 然后您必须测试 if (e.getKeyCode () == e.VK_ENTER) 而不是使用整个文本,您只需使用光标前最后一行的子字符串

//ignores the special case of an empty line
//so a test for \n before the Caret or the Caret still being at 0 is necessary
int endpos = tf.getCaret().getMark();
int startpos = tf.getText().substring(0, endpos-1).lastIndexOf('\n')+1;

用于输入字符串。因为否则每次按下 Enter 时您都会阅读整个 TextArea。

关于java - 将 System.in 重定向到 swing 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9244108/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com