我在javaclass中有简单的代码。
public class JavaApplication1 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
System.out.println("hello");
}
}
我需要在运行时在Jtextfield中显示“hello”输出...作为一个更新鲜的我不知道该怎么做..
答案 0 :(得分:2)
您需要TextAreaOutputStream,例如
import java.io.IOException;
import java.io.OutputStream;
import javax.swing.JTextArea;
/**
* TextAreaOutputStream creates an outputstream that will output to the
* given textarea. Useful in setting System.out
*/
public class TextAreaOutputStream extends OutputStream {
public static final int DEFAULT_BUFFER_SIZE = 1;
JTextArea mText;
byte mBuf[];
int mLocation;
public TextAreaOutputStream(JTextArea component) {
this(component, DEFAULT_BUFFER_SIZE);
}
public TextAreaOutputStream(JTextArea component, int bufferSize) {
mText = component;
if (bufferSize < 1) bufferSize = 1;
mBuf = new byte[bufferSize];
mLocation = 0;
}
@Override
public void write(int arg0) throws IOException {
//System.err.println("arg = " + (char) arg0);
mBuf[mLocation++] = (byte)arg0;
if (mLocation == mBuf.length) {
flush();
}
}
public void flush() {
mText.append(new String(mBuf, 0, mLocation));
mLocation = 0;
}
}
创建它,然后使用System.setOut(OutputStream)将System.out发送到文本区域
答案 1 :(得分:1)
最简单的方法是:首先用文本框设置一个框架,然后直接打印到它。
public static void main(String[] args) {
JFrame frame = new JFrame();
JTextField field = new JTextField();
frame.add(field);
frame.pack();
frame.setVisible(true);
OutputStream out = new OutputStream() {
@Override
public void write(int b) throws IOException {
}
};
class JTextFieldPrintStream extends PrintStream {
public JTextFieldPrintStream(OutputStream out) {
super(out);
}
@Override
public void println(String x) {
field.setText(x);
}
};
JTextFieldPrintStream print = new JTextFieldPrintStream(out);
System.setOut(print);
System.out.println("hello");
}