简体   繁体   中英

how to create s.th. like a output stream in a function in java?

I want to solve the following problem: I have a GUI class with some JTextArea . And I'm also writing my own class, lets call it Foo .

Actually, I have all my calculations in the GUI class. They just use s.th. like myText.append(...) to write some output into the GUI.

Now I want to put all the calculations into my new class Foo . The problem : How can I create a method, which get the JTextArea from the GUI as a input and then just use it as before to write some output text into it. I don't want to have this as a return value of the method!

Is this possible?

What you need is a mapper or adapter, ie something that accepts the methods from one interface and translates them into method calls of another interface. In your case, I suggest to use Writer over OutputStream to avoid all the encoding issues. Try this code:

public Foo extends Writer {
    private JTextArea textArea;

    public Foo( JTextArea textArea ) {
        this.textArea = textArea;
    }

    public void write(char cbuf[], int off, int len) throws IOException {
        String text = new String( cbuff, off, len );
        textArea.append( text );
    }

    public void close() { }
    public void flush() { }
}

If you really need an OutputStream , have a look at OutputStreamWriter to convert between bytes and Unicode characters.

Something like this...

public class Foo {
    public void writeInfoToTextArea(JTextArea textArea /*, other parms here */) {
        textArea.setText(...);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM