2017-09-14 41 views
-2

我在javaclass中有簡單的代碼。如何從system.out.println顯示輸出到Jtextfield

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顯示「你好」輸出運行時......作爲一個新鮮的,我不知道該怎麼做..

回答

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"); 
} 
+0

謝謝您的回答。 。它正在工作.. – user5809644

+0

謝謝,但ControlAltDel是正確的:我應該重定向系統輸出。我調整了我的答案。新代碼中的 – JensS

+0

「System.out.println(」hello「);」不顯示..輸出...只有jframe顯示... – user5809644

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發送到文本區域