Search code examples
javaiosystem.in

Java System.in not working with custom stream


I am currently designing a chat application in Java. Therefore I created my own JFrame. All contents written to System.out are written into a JTextArea and I want to redirect System.in to use my JTextField. I wrote a simple class what should handle this:

public class InputField extends InputStream implements KeyListener {
    private JTextField textField;
    private String text = null;


    public InputField(JTextField textField){
        this.textField = textField;

        textField.addKeyListener(this);
    }

    @Override
    public int read() throws IOException {
        //System.out.println("CALLED!");
        while (text == null)
            ;

        int b;

        if (Objects.equals(text, "")) {
            b = -1;
            text = null;
        } else {
            b = text.charAt(0);
            text = text.substring(1, text.length());
        }

        // System.out.println("GIVING: " + b);

        return b;
    }

    @Override
    public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_ENTER) {
            text = textField.getText();
            System.out.println("ENTER: "+ text);
            textField.setText("");
        }
    }

    @Override
    public void keyTyped(KeyEvent e) {}

    @Override
    public void keyReleased(KeyEvent e) {}
}

My reading mechanism:

StringBuilder cmd = new StringBuilder();
int b;

try {
    while ((b = System.in.read()) != -1)
        cmd.append(b);
    // Do something with cmd
} catch (IOException e){}

The first time I input any text and press enter, it works just fine. After outputting a message the read() function is called, but if I try to enter more text the read() function isn't called anymore. Any suggestions to fix this?

Take a look at this image.


Solution

  • The first time you hit enter, it sets the text to "". Then this block sets b = -1:

    if (Objects.equals(text, "")) {
            b = -1;
    

    Which is the value that read returns, which makes your main loop finish.