栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

将System.in重定向到摆动组件

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

将System.in重定向到摆动组件

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

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以来​​已经有一段时间了,所以我可能不了解最新的模式。您可能还应该重载,

intavailable()
但是我的示例仅包含使它与
BufferedReader
s
readLine()
函数一起工作的最低要求。

编辑: 为了使它起作用,

JTextField
您必须使用
implements KeyListener
而不是,
implementsActionListener
然后
addKeyListener(...)
在textarea上使用。您需要代替的功能
actionPerformed(...)
publicvoid 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 necessaryint endpos = tf.getCaret().getMark();int startpos = tf.getText().substring(0, endpos-1).lastIndexOf('n')+1;

输入字符串。因为否则,您每次按Enter时都将读取整个textarea。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/410447.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号