begin process at 2010 02 10 00:28:34
  Trouver un code source :
 
dans
 
Accueil > 

Code

 > 

Astuces

 > REDIRECTION DES FLUX SYSTEM.OUT ET SYSTEM.ERR DANS UNE JTEXTAREA

REDIRECTION DES FLUX SYSTEM.OUT ET SYSTEM.ERR DANS UNE JTEXTAREA


 Information sur la source

 Description

Au lieu d'afficher des JOptionPane à toutes les erreurs, laisser l'utilisateur regarder dans la console intégrer.

A améliorer : La sortie d'erreur n'est pas en rouge.

Source

  • /*
  • * Console.java
  • *
  • * Created on 11 octobre 2007, 10:12
  • *
  • */
  • import java.awt.BorderLayout;
  • import java.awt.Color;
  • import java.awt.Font;
  • import java.awt.event.ActionEvent;
  • import java.awt.event.ActionListener;
  • import java.awt.event.WindowEvent;
  • import java.beans.PropertyVetoException;
  • import java.io.IOException;
  • import java.io.PipedInputStream;
  • import java.io.PipedOutputStream;
  • import java.io.PrintStream;
  • import javax.swing.JButton;
  • import javax.swing.JInternalFrame;
  • import javax.swing.JScrollPane;
  • import javax.swing.JTextArea;
  • import javax.swing.event.InternalFrameEvent;
  • import javax.swing.event.InternalFrameListener;
  • /**
  • * Redirection des flux System.out et System.err dans une JTextArea
  • * @author Ronan Martin
  • */
  • public class Console extends JInternalFrame implements InternalFrameListener, ActionListener, Runnable {
  • private JTextArea textArea;
  • private Thread reader;
  • private Thread reader2;
  • private boolean quit;
  • private final PipedInputStream pin=new PipedInputStream();
  • private final PipedInputStream pin2=new PipedInputStream();
  • Thread errorThrower;
  • /** Constructeur par défaut de Console
  • * Le but du jeu est de redirigé les sorties classiques, que ce soit
  • * sout ou pour serr.
  • * Pour cela nous allons utiliser deux threads indépendants
  • *
  • * Création de l'objet et de la fenetre
  • */
  • public Console() {
  • setTitle("Console");
  • textArea=new JTextArea();
  • textArea.setEditable(false);
  • textArea.setFont(new Font(Font.DIALOG,Font.PLAIN,10));
  • JButton button=new JButton("Effacer");
  • getContentPane().setLayout(new BorderLayout());
  • getContentPane().add(new JScrollPane(textArea),BorderLayout.CENTER);
  • getContentPane().add(button,BorderLayout.SOUTH);
  • setVisible(true);
  • this.addInternalFrameListener(this);
  • button.addActionListener(this);
  • redirect();
  • setDefaultCloseOperation(HIDE_ON_CLOSE);
  • setSize(300,200);
  • setClosable(true);
  • setIconifiable(true);
  • setMaximizable(true);
  • setResizable(true);
  • }
  • /**
  • * Redirection des flux
  • *
  • */
  • private void redirect(){
  • try {
  • PipedOutputStream pout=new PipedOutputStream(pin);
  • System.setOut(new PrintStream(pout,true));
  • } catch (java.io.IOException io) {
  • textArea.append("Couldn't redirect STDOUT to this console\n"+io.getMessage());
  • } catch (SecurityException se) {
  • textArea.append("Couldn't redirect STDOUT to this console\n"+se.getMessage());
  • }
  • try {
  • PipedOutputStream pout2=new PipedOutputStream(pin2);
  • System.setErr(new PrintStream(pout2,true));
  • } catch (java.io.IOException io) {
  • textArea.append("Couldn't redirect STDERR to this console\n"+io.getMessage());
  • } catch (SecurityException se) {
  • textArea.append("Couldn't redirect STDERR to this console\n"+se.getMessage());
  • }
  • quit=false; // signals the Threads that they should exit
  • // Starting two seperate threads to read from the PipedInputStreams
  • //
  • reader = new Thread(this);
  • reader.setDaemon(true);
  • reader.start();
  • reader2=new Thread(this);
  • reader2.setDaemon(true);
  • reader2.start();
  • errorThrower=new Thread(this);
  • errorThrower.setDaemon(true);
  • errorThrower.start();
  • }
  • public synchronized void actionPerformed(ActionEvent evt) {
  • textArea.setText("");
  • }
  • /**
  • * Lancement des threads
  • */
  • public synchronized void run() {
  • try {
  • while (Thread.currentThread()==reader) {
  • try { this.wait(100);}catch(InterruptedException ie) {}
  • if (pin.available()!=0) {
  • String input=this.readLine(pin);
  • textArea.append(input);
  • }
  • if (quit) return;
  • }
  • while (Thread.currentThread()==reader2) {
  • try { this.wait(100);}catch(InterruptedException ie) {}
  • if (pin2.available()!=0) {
  • String input=this.readLine(pin2);
  • textArea.append(input);
  • }
  • if (quit) return;
  • }
  • } catch (Exception e) {
  • textArea.append("\nConsole reports an Internal error.");
  • textArea.append("The error is: "+e);
  • }
  • }
  • /**
  • * Lecture de la sortie standard
  • */
  • protected synchronized String readLine(PipedInputStream in) throws IOException {
  • String input="";
  • do
  • {
  • int available=in.available();
  • if (available==0) break;
  • byte b[]=new byte[available];
  • in.read(b);
  • input=input+new String(b,0,b.length);
  • }while( !input.endsWith("\n") && !input.endsWith("\r\n") && !quit);
  • return input;
  • }
  • public void windowOpened(WindowEvent e) {
  • }
  • public void windowIconified(WindowEvent e) {
  • }
  • public void windowDeiconified(WindowEvent e) {
  • }
  • public void windowActivated(WindowEvent e) {
  • }
  • public void windowDeactivated(WindowEvent e) {
  • }
  • public void internalFrameOpened(InternalFrameEvent e) {
  • }
  • public void internalFrameClosing(InternalFrameEvent e) {
  • setVisible(false);
  • }
  • /**
  • * Est appelé automatiquement a la sortie du programme
  • */
  • public void internalFrameClosed(InternalFrameEvent e) {
  • quit=true;
  • this.notifyAll(); // stop all threads
  • try { reader.join(1000);pin.close(); } catch (Exception ex){}
  • try { reader2.join(1000);pin2.close(); } catch (Exception ex){}
  • }
  • public void internalFrameIconified(InternalFrameEvent e) {
  • }
  • public void internalFrameDeiconified(InternalFrameEvent e) {
  • }
  • public void internalFrameActivated(InternalFrameEvent e) {
  • }
  • public void internalFrameDeactivated(InternalFrameEvent e) {
  • }
  • }
/*
 * Console.java
 *
 * Created on 11 octobre 2007, 10:12
 *
 */


import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.beans.PropertyVetoException;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintStream;
import javax.swing.JButton;
import javax.swing.JInternalFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.event.InternalFrameEvent;
import javax.swing.event.InternalFrameListener;

/**
 * Redirection des flux System.out et System.err dans une JTextArea
 * @author Ronan Martin
 */
public class Console extends JInternalFrame implements InternalFrameListener, ActionListener, Runnable {
    private JTextArea textArea;
    private Thread reader;
    private Thread reader2;
    private boolean quit;
    
    private final PipedInputStream pin=new PipedInputStream();
    private final PipedInputStream pin2=new PipedInputStream();
    Thread errorThrower;
    
    /** Constructeur par défaut de  Console
     * Le but du jeu est de redirigé les sorties classiques, que ce soit
     * sout ou pour serr.
     * Pour cela nous allons utiliser deux threads indépendants
     * 
     * Création de l'objet et de la fenetre
     */
    
    public Console() {
        setTitle("Console");
        textArea=new JTextArea();
        textArea.setEditable(false);
        textArea.setFont(new Font(Font.DIALOG,Font.PLAIN,10));
        JButton button=new JButton("Effacer");
        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(new JScrollPane(textArea),BorderLayout.CENTER);
        getContentPane().add(button,BorderLayout.SOUTH);
        setVisible(true);
        this.addInternalFrameListener(this);
        button.addActionListener(this);
        redirect();
        setDefaultCloseOperation(HIDE_ON_CLOSE);
        setSize(300,200);
        setClosable(true);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        
    }
    
    /**
     * Redirection des flux
     *
     */
    private void redirect(){
        try {
            PipedOutputStream pout=new PipedOutputStream(pin);
            System.setOut(new PrintStream(pout,true));
        } catch (java.io.IOException io) {
            textArea.append("Couldn't redirect STDOUT to this console\n"+io.getMessage());
        } catch (SecurityException se) {
            textArea.append("Couldn't redirect STDOUT to this console\n"+se.getMessage());
        }
        
        try {
            PipedOutputStream pout2=new PipedOutputStream(pin2);
            System.setErr(new PrintStream(pout2,true));
        } catch (java.io.IOException io) {
            textArea.append("Couldn't redirect STDERR to this console\n"+io.getMessage());
        } catch (SecurityException se) {
            textArea.append("Couldn't redirect STDERR to this console\n"+se.getMessage());
        }
        
        quit=false; // signals the Threads that they should exit
        
        // Starting two seperate threads to read from the PipedInputStreams
        //
        
        reader = new Thread(this);
        reader.setDaemon(true);
        reader.start();
        reader2=new Thread(this);
        reader2.setDaemon(true);
        reader2.start();
        errorThrower=new Thread(this);
        errorThrower.setDaemon(true);
        errorThrower.start();
    }

    
    public synchronized void actionPerformed(ActionEvent evt) {
        textArea.setText("");
    }
    /**
     * Lancement des threads
     */
    public synchronized void run() {
        try {
            while (Thread.currentThread()==reader) {
                try { this.wait(100);}catch(InterruptedException ie) {}
                if (pin.available()!=0) {
                    String input=this.readLine(pin);
                    textArea.append(input);
                }
                if (quit) return;
            }
            
            while (Thread.currentThread()==reader2) {
                try { this.wait(100);}catch(InterruptedException ie) {}
                if (pin2.available()!=0) {
                    String input=this.readLine(pin2);
                    textArea.append(input);
                }
                if (quit) return;
            }
        } catch (Exception e) {
            textArea.append("\nConsole reports an Internal error.");
            textArea.append("The error is: "+e);
        }
    }
    
    /**
     * Lecture de la sortie standard
     */
    protected synchronized String readLine(PipedInputStream in) throws IOException {
        String input="";
        do
        {
            int available=in.available();
            if (available==0) break;
            byte b[]=new byte[available];
            in.read(b);
            input=input+new String(b,0,b.length);
        }while( !input.endsWith("\n") &&  !input.endsWith("\r\n") && !quit);
        return input;
    }

    public void windowOpened(WindowEvent e) {
    }

    public void windowIconified(WindowEvent e) {
    }

    public void windowDeiconified(WindowEvent e) {
    }

    public void windowActivated(WindowEvent e) {
    }

    public void windowDeactivated(WindowEvent e) {
    }

    public void internalFrameOpened(InternalFrameEvent e) {
    }

    public void internalFrameClosing(InternalFrameEvent e) {
     setVisible(false);
    }

    /**
     * Est appelé automatiquement a la sortie du programme
     */
    public void internalFrameClosed(InternalFrameEvent e) {
        
        quit=true;
        this.notifyAll(); // stop all threads
        try { reader.join(1000);pin.close();   } catch (Exception ex){}
        try { reader2.join(1000);pin2.close(); } catch (Exception ex){}
    }

    public void internalFrameIconified(InternalFrameEvent e) {
    }

    public void internalFrameDeiconified(InternalFrameEvent e) {
    }

    public void internalFrameActivated(InternalFrameEvent e) {
    }

    public void internalFrameDeactivated(InternalFrameEvent e) {
    }
    
}

 Conclusion

En espérant que ça peut aider certains ...


 Sources du même auteur

Source avec Zip Source avec une capture APPLET : REDIMENSIONNEMENT D'UNE IMAGE AVANT UPLOAD
Source avec Zip Source avec une capture FEUILLE DE PROPRIÉTÉS
Source avec une capture VISUALISER DES JOURNAUX LOG4J
Source avec Zip Source avec une capture FENÊTRE POUR INTERROGER UNE BASE DE DONNÉE

 Sources de la même categorie

Source avec Zip CLASS DEMINEUR par Niidhogg
AJOUTER LE MAIL À LA LISTE DE CONTACT HOTMAIL POUR EVOLUTION... par sarathai
Source avec Zip ENVOI MAIL AVEC JAVA par mdahmoune
Source avec Zip Source avec une capture JADE PAR LA PRATIQUE par mdahmoune
CHUNKEDXML, LIRE DU XML PAR MORCEAU par AlexN

 Sources en rapport avec celle ci

Source avec Zip Source avec une capture CONVERTIR ENTRE LES BASES 10,2,8 ET 16 par 2mohamed2
CONSOLE STANDARD IMPLEMENTABLE AVEC UN INPUTLOGLISTENER par broumbroum
Source avec Zip Source avec une capture ECRIRE EN COULEURS SUR LA CONSOLE(JNI) par Twinuts
Source avec Zip Source avec une capture CONSOLE POUR ORACLE par melodymaker
Source avec Zip Source avec une capture JEU DE DONJON EN JFRAME par grattier

Commentaires et avis

Commentaire de uhrand le 24/10/2007 19:17:14

J'ai beaucoup apprécié cette source.
Pour afficher les erreurs en rouge, il faudra prendre une JTextPane. Exemple:
[code]
import javax.swing.text.*;
...
    private JTextPane textPane;
    private StyledDocument textArea;
    private SimpleAttributeSet red;
...
    public Console() {
...
        textPane = new JTextPane();
        textArea = textPane.getStyledDocument();
        red = new SimpleAttributeSet();
        StyleConstants.setForeground(red, Color.red);
...
    }
...
            try {
                textArea.insertString(textArea.getLength(), "Couldn't redirect STDOUT to this console\n" + io.getMessage(), null);
            } catch (BadLocationException exception) {            }
...
            try {
                textArea.insertString(textArea.getLength(), "Couldn't redirect STDOUT to this console\n" + se.getMessage(), null);
            } catch (BadLocationException exception) {            }
...
            try {
                textArea.insertString(textArea.getLength(), "Couldn't redirect STDERR to this console\n" + io.getMessage(), null);
            } catch (BadLocationException exception) {            }
...
            try {
                textArea.insertString(textArea.getLength(), "Couldn't redirect STDERR to this console\n" + se.getMessage(), null);
            } catch (BadLocationException exception) {            }
...
    public synchronized void actionPerformed(ActionEvent evt) {
        try {
            textArea.remove(0, textArea.getLength());
        } catch (BadLocationException exception) {        }
    }
...
    public synchronized void run() {
        try {
            while (Thread.currentThread() == reader) {
...
                    textArea.insertString(textArea.getLength(), input, null);
...
            }
            while (Thread.currentThread() == reader2) {
...
                    textArea.insertString(textArea.getLength(), input, red);
...
            }
        } catch (Exception e) {
            try {
                textArea.insertString(textArea.getLength(), "\nConsole reports an Internal error.", null);
                textArea.insertString(textArea.getLength(), "The error is: " + e, null);
            } catch (BadLocationException exception) {            }
        }
...
[/code]

Commentaire de komes28 le 03/12/2007 16:17:08

Je ne vois pas comment le code fonctionne. Je vais vous expliquer ce que je veux faire et vous me diriez si c est possible avec ce code. Je veux créer une console de débogage pour un logiciel. c a dire que tout les strings générer pas mon code sont system.out (afficher) en console. J aimerais savoir si je peux integrer cette console a mon code de facon a les voir directement. Un exemple serait bien apprécier. Je vous remercie d'avance

Commentaire de twinser le 03/12/2007 19:30:42

Bien sur, c'est meme le but de cette console, voici un exemple pour intégrer la console :
/*
* Test.java
* Ce fichier permet de tester Console.java qui est une JInternalFrame
* Il est possible d'utiliser Console.java en tant que Frame ou JDialog, il suffit
* de modifier l'héritage.
* Remarque : les flux ne sont pas réinitialisés à la fermeture de la JInternalFrame.
* Attention au package, les deux classes sont mises dans le package par défaut.
*/


import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

/**
* @author ronan
*/
public class Test {
    public Test() {
        // Préparation d'une JFrame'
        JFrame frame = new JFrame("Test");
        frame.setSize(600,600);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.setLocationRelativeTo(SwingUtilities.getRoot(frame));
        JDesktopPane desktop = new JDesktopPane();
        frame.add(desktop);
        
        Console console = new Console();
        desktop.add(console);
        
        frame.setVisible(true);
        
        System.out.println("un petit test");
    }
  
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new Test();
    }
}

Commentaire de komes28 le 04/12/2007 07:09:36

merci beaucoup pour votre prompt reponse...

Commentaire de herve91fr le 13/05/2008 22:13:47

Pourquoi faire si compliqué ?

JTextArea ta = new JTextArea(16, 80);
PrintStream ps = new PrintStream(new TextAreaOutputStream(ta));
System.setOut(ps);
System.setErr(ps);

class TextAreaOutputStream extends OutputStream {

   private JTextArea ta;

   public TextAreaOutputStream(JTextArea ta) {
      this.ta = ta;
   }

   public synchronized void write(int b) throws IOException {
      ta.append(String.valueOf((char) b));
   }
}

 Ajouter un commentaire


Discussions en rapport avec ce code source dans le forum

Compilation en mode console! [ par Marneus ] Salut a tous, j'aimerais que mon petit prog que j'ai fait soit executable en console comment faire?Merci de votre aide! Changer la couleur du texte en mode console [ par Sw1tch ] Salut,J'aimerai changer le couleur du texte que j'affiche dans la console avec System.out.print("Salut") ; et par la même occasion savoir s'il est pos imprimer la console [ par stickasia ] j'aimerai imprimer la consol via d'un bouton d'une interface graphique qq1 pourrait il m'aider???? Analyse trame [ par hoffnanard ] je souhaite enregistrer dans un fichier ( texte par exemple )des trame ethernet comment faire ?? merci Legrand Changer la couleur du texte dans une console [ par Mithrandir62 ] hello,Je sais pas si cela interesse quelqu'un mais j'ai la solution pour ecrire dans une console de de differentes couleurs, cela ne fonctionne que so Saisie au clavier (console) [ par FurySpike ] Bonjour a tous, j'aimerais savoir s'il y a moyen de lire des nombre au clavier (negatif et positif) sans avoir recours a une nouvelle class (comme ce effacer l'ecran en mode console [ par cloud21 ] salut,je voudrais savoir quelle est l'equivalent (mode console) en javadu clrscr(); en C?merci pour vos réponse! comment vider l'écran en mode console [ par johanb ] bonjour à tous, alors voilà, je viens de commencer dans le java et j'aimerais savoir quelle librairie utiliser pour vider l'écran dans un programme en Lecture impossible d'un fichier dans une console DOS [ par kobee12 ] Bonjour a tous,Voila j'ai cree un prgm qui fait appel a des fichiers.Quand j'execute mon prgm a partir de JBuilder, ca fonctionne bien, par contre qua classe vector [ par Jhio ] Est-ce qu'on peut en utilisant la methode getElementAt(int) de la classe Vector de recevoir quelquechose de plus précis qu'un Object, mai plutot du ty


Nos sponsors


Sondage...

CalendriCode

Février 2010
LMMJVSD
1234567
891011121314
15161718192021
22232425262728

Consulter la suite du CalendriCode

 
Développement réalisé par Nicolas SOREL (Nix) avec l'aide de : Cyril DURAND et Emmanuel (EBArtSoft), Merci à Vincent pour ses précieux conseils.
CodeS-SourceS.com© Toute reproduction même partielle est interdite sauf accord écrit du Webmaster
CodeS-SourceS.com© est une marque déposée tous droits réservés

Google Coop CodeS-SourceS Google Coop CodeS-SourceS
Temps d'éxécution de la page : 0,515 sec (3)

Nous contacter | Annoncer sur CodeS-SourceS | Mentions légales