簡體   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