![](/img/trans.png)
[英]In JSP/Java how can I replace getter/setter by s.th. more generic?
[英]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.