2017-09-14 2 views
-2

J'ai un code simple dans javaclass.comment afficher la sortie à Jtextfield à partir de system.out.println

public class JavaApplication1 { 

    /** 
    * @param args the command line arguments 
    */ 
    public static void main(String[] args) { 
     // TODO code application logic here 
     System.out.println("hello"); 
    } 

} 

Je dois montrer le « bonjour » sortie en cours d'exécution ... JTextField en tant que plus fraîche, je ne sais pas comment le faire ..

Répondre

1

manière la plus simple est la suivante: Première installation d'un cadre avec la zone de texte, puis imprimer directement sur elle.

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

merci pour votre réponse. Cela fonctionne .. – user5809644

+0

Merci, mais ControlAltDel a raison: je devrais rediriger la sortie du système. J'ai ajusté ma réponse à cela. – JensS

+0

dans le nouveau code "System.out.println (" hello ");" pas d'affichage .. la sortie ... seulement jframe montre ... – user5809644

2

Vous avez besoin d'un TextAreaOutputStream, par exemple

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;   
     } 

    } 

Créer, utilisez alors System.setOut (OutputStream) pour envoyer votre System.out à la zone de texte