繁体   English   中英

如何创建某事 像在Java函数中的输出流?

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

我想解决以下问题:我有一个带有一些JTextArea的GUI类。 我也在写自己的课,叫它Foo

实际上,我所有的计算都在GUI类中。 他们只用s.th. myText.append(...) ,将一些输出写入GUI。

现在,我想将所有计算结果放入我的新类Foo 问题 :如何创建一种方法,该方法从GUI获得JTextArea作为输入,然后像以前一样使用它来向其中写入一些输出文本。 我不想将此作为方法的返回值!

这可能吗?

您需要的是映射器或适配器,即从一个接口接受方法并将其转换为另一个接口的方法调用的对象。 对于您的情况,我建议在OutputStream上使用Writer以避免所有编码问题。 试试这个代码:

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() { }
}

如果确实需要OutputStream ,请查看OutputStreamWriter在字节和Unicode字符之间进行转换。

像这样

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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