2010-12-12 4 views
2

Bonjour Est-il possible de dessiner dans un JPanel ce que renvoie la console java? avez-vous un tutoriel à suivre? merci swConsole Java JPanel

+1

Vous pouvez ajouter "Swing" aux tags de votre question pour attirer le forum Swing experts. :) –

Répondre

2

Première lecture depuis la console. Pour ce faire, utilisez System.setOut(). Utilisez ByteOutputStream, écrivez là et lisez depuis leur. Vous obtiendrez ce que votre programme imprime sur le système. Utilisez maintenant TextArea ou JScrollPane pour présenter le texte.

6

Je ne me souviens pas où j'ai trouvé, mais je l'ai délivré le flux de sortie à un JTextArea tenue dans un JPanel en utilisant une classe que j'appelle TextAreaOutputStream:

import java.io.IOException; 
import java.io.OutputStream; 
import javax.swing.JTextArea; 
import javax.swing.SwingUtilities; 

public class TextAreaOutputStream extends OutputStream { 

    private final JTextArea textArea; 
    private final StringBuilder sb = new StringBuilder(); 
    private String title; 

    public TextAreaOutputStream(final JTextArea textArea, String title) { 
     this.textArea = textArea; 
     this.title = title; 
     sb.append(title + "> "); 
    } 

    @Override 
    public void flush() { 
    } 

    @Override 
    public void close() { 
    } 

    @Override 
    public void write(int b) throws IOException { 

     if (b == '\r') 
      return; 

     if (b == '\n') { 
      final String text = sb.toString() + "\n"; 
      SwingUtilities.invokeLater(new Runnable() { 
       public void run() { 
        textArea.append(text); 
       } 
      }); 
      sb.setLength(0); 
      sb.append(title).append("> "); 
     } 

     sb.append((char) b); 
    } 
} 

Je puis re directe la sortie standard Écoutez cet objet comme Alex le mentionne dans sa réponse ci-dessus.

+1

'sb.append (title) .append ("> ");' serait probablement plus efficace. –

+0

@DavidConrad: en effet, cela éviterait une concaténation de chaîne. Merci, et réponse éditée. –

2

Créez une sous-classe de FilterOutputStream pour répercuter tout sur un JTextArea.

class Echo extends FilterOutputStream { 

    private final JTextArea text; 

    public Echo(OutputStream out, JTextArea text) { 
     super(out); 
     if (text == null) throw new IllegalArgumentException("null text"); 
     this.text = text; 
    } 

    @Override 
    public void write(int b) throws IOException { 
     super.write(b); 
     text.append(Character.toString((char) b)); 
     // scroll to end? 
    } 

    // overwrite the other write methods for better performance 
} 

et remplacer la sortie standard:

JTextArea text = new JTextArea(); 
    System.setOut(new PrintStream(new Echo(System.out, text)));