Java-如何扩展InputStream从JTextField读取? [英] Java-How to extend InputStream to read from a JTextField?

查看:190
本文介绍了Java-如何扩展InputStream从JTextField读取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从事一个项目,我通过一个类似于控制台的小窗口开始运行Java应用程序.由于这里有一个很棒的社区,我设法解决了从过程输出数据的问题,但是我的命令行应用程序由于没有输入流,运行将不断产生错误.

Working on a project I got into running java applications through a small console-like window. Thanks to the wonderful community in here I managed to solve the problem with outputting the data from a proccess but my command-line applications running will constantly give errors as there is no input stream.

基于该线程中的最后一个有用答复,我想我将以类似的方式实现JTextFieldInputStream extends InputStream的实现,但是在javadocs中以及整个google和互联网中查找某些类,这些类的确使我真正找不到任何解释该怎么做的东西.这.

Based on the last helpful reply in that thread I suppose I shall approach similarly the JTextFieldInputStream extends InputStream implementation, but looking in the javadocs and throughout google and the internet for some class that does just that I really found nothing explaining how to do this.

因此,我想为其提供一些链接,示例,教程和示例代码,就像在上一个主题中一样. 给我一个扩展InputStream的类,当我按Enter时可以扩展为从JTextField读取,我将通过实现它并使它正常工作来完成剩下的工作!预先感谢!

So I am asking for some link, example, tutorial, sample code for it just like in the previous topic. Give me just a class that extends InputStream and can be extended to read from a JTextField when I press Enter and I will do the rest with implementing this and making it work! Thanks in advance!

推荐答案

此实现如何

import java.io.IOException;
import java.io.InputStream;

import javax.swing.JTextField;


public class JTextFieldInputStream extends InputStream {
    byte[] contents;
    int pointer = 0;

    public JTextFieldInputStream(final JTextField text) {

        text.addKeyListener(new KeyAdapter() {
            @Override
            public void keyReleased(KeyEvent e) {
                if(e.getKeyChar()=='\n'){
                    contents = text.getText().getBytes();
                    pointer = 0;
                    text.setText("");
                }
                super.keyReleased(e);
            }
        });
    }

    @Override
    public int read() throws IOException {
        if(pointer >= contents.length) return -1;
        return this.contents[pointer++];
    }

}

要使用此输入流,请执行以下操作

to use this input stream, do the following

 InputStream in = new JTextFieldInputStream( someTextField );
 char c;
 while( (c = in.read()) != -1){
    //do whatever with c
 }

仅当我按Enter键时它才读吗?

does it read only when I hit enter?

在调用in.read()时读取,如果返回值-1表示流的末尾

it reads when you call in.read() if the return value -1 it means end of the stream

(并且我将能够进行修改,以使Enter键清空JTextField吗?)

(And will I be able to modify so that the Enter key empties the JTextField?)

您需要添加一个动作侦听器,此功能与输入流的工作无关

you need to add an action listener and this functionality has nothing to do with the job of input stream

这篇关于Java-如何扩展InputStream从JTextField读取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆