|
Trouver une ressource
Vous ne trouvez pas de réponse à votre problème ? Alors posez la question dans le forum. Souvenez-vous qu'il n'y a jamais de question bête, mais rester dans l'ignorance parce que l'on n'ose pas poser une question, ça c'est une erreur !
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
Sources de la même categorie
Sources en rapport avec celle ci
Commentaires et avis
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
|
Téléchargements
Logiciels à télécharger sur le même thème :
|