Search code examples
javaswinginputstreamjtextfield

Java-How to extend InputStream to read from a JTextField?


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.

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.

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!


Solution

  • How about this implementation

    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
     }
    

    does it read only when I hit enter?

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

    (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