Afficher le résultat de la console, dans une fenetre a part

Fermé
khalous91 Messages postés 18 Date d'inscription mercredi 15 avril 2015 Statut Membre Dernière intervention 17 juin 2015 - 27 avril 2015 à 10:24
 Utilisateur anonyme - 27 avril 2015 à 16:20
Salut,
Alors j'aimerai afficher le résultat de ma " console" dans une JFrame à part.
Je me suis renseigné mais en vain... je sais que c'estun problème de flux mais comment y remédier ? :/
J'ai mes deux classes ci-dessous :

classe SimpleFenetre :
 import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;


public class simplefenetre extends JFrame {

private JPanel contentPane;
private static JTextField zoneB;
private static JTextField valueE;
private static JTextField zoneE;
private static JTextField valueB;
private JTextField textField_4;



public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
simplefenetre frame = new simplefenetre();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

/* Le constructeur */

public simplefenetre() {
// On créer un groupe de boutons .
ButtonGroup groupeDeBoutons = new ButtonGroup();


setTitle("Traiter vos fichiers");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);

// Button "OK"
JButton btnOk = new JButton("OK");
btnOk.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// On lit les 5 champs

String ZONE_B = zoneB.getText();
String ZONE_E = zoneE.getText();
String VALUE_B = valueB.getText();
String VALUE_E = valueE.getText();
String PATH = textField_4.getText();

// On appelle la méthode de l'autre classe
new Finally().traiterFichier(ZONE_B, ZONE_E, VALUE_B, VALUE_E, PATH);
}

});

// mise en relation du bouton ok avec les deux autres
groupeDeBoutons.add(btnOk);
btnOk.setBounds(243, 228, 58, 23);
contentPane.add(btnOk);

// Button "PARCOURIR"

JButton btnParcourir = new JButton("PARCOURIR");
btnParcourir.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
browseFile(); // sert au bouton PARCOURIR d'aller chercher un fichier x
}
});

// mise en relation du bouton PARCOURIR avec les deux autres
groupeDeBoutons.add(btnParcourir);
btnParcourir.setBounds(304, 56, 120, 23);
contentPane.add(btnParcourir);

// Button "ANNULER"

JButton btnAnnuler = new JButton("ANNULER");
btnAnnuler.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});

// mise en relation du bouton ANNULER avec les deux autres
groupeDeBoutons.add(btnAnnuler);
btnAnnuler.setBounds(311, 228, 113, 23);
contentPane.add(btnAnnuler);

// On créer les composants de saisies .

zoneB = new JTextField("#>");
zoneB.setBounds(116, 112, 86, 20);
contentPane.add(zoneB);
zoneB.setColumns(10);

zoneE = new JTextField("#<");
zoneE.setBounds(116, 145, 86, 20);
contentPane.add(zoneE);
zoneE.setColumns(10);

valueB = new JTextField("{");
valueB.setBounds(116, 176, 86, 20);
contentPane.add(valueB);
valueB.setColumns(10);

valueE = new JTextField("}");
valueE.setBounds(116, 207, 86, 20);
contentPane.add(valueE);
valueE.setColumns(10);


JLabel lblNewLabel = new JLabel("VALUE_B ");
lblNewLabel.setBounds(10, 179, 86, 14);
contentPane.add(lblNewLabel);

JLabel lblNewLabel_1 = new JLabel("ZONE_B");
lblNewLabel_1.setBounds(10, 115, 73, 14);
contentPane.add(lblNewLabel_1);

JLabel lblNewLabel_2 = new JLabel("VALUE_E");
lblNewLabel_2.setBounds(10, 210, 73, 14);
contentPane.add(lblNewLabel_2);

JLabel lblNewLabel_3 = new JLabel("ZONE_E");
lblNewLabel_3.setBounds(10, 148, 73, 14);
contentPane.add(lblNewLabel_3);

textField_4 = new JTextField();
textField_4.setBounds(10, 57, 192, 20);
contentPane.add(textField_4);
textField_4.setColumns(10);



}

private void browseFile() {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Choisir le fichier...");
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser.setMultiSelectionEnabled(false);
if ( !textField_4.getText().isEmpty() ) { // faire bien attention : bien faire correspondre notre textField choisi, ici le textField_4
fileChooser.setSelectedFile(new File(zoneB.getText()));
}
// il y a plein d'autres méthodes pour customiser le composant (filtre sur les fichiers par exemple) : voir doc.
if ( fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION ) {
textField_4.setText( fileChooser.getSelectedFile().getAbsolutePath().toString() );
}
}

}


classe Finally :

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashSet;

public class Finally {


public static final String ZONE_B = "#>"; // le début de la sous partie de texte à extraire
public static final String ZONE_E = "#<"; // la fin de la sous partie de texte à extraire
public static final String VALUE_B = "{"; // le début d'un mot à extraire
public static final String VALUE_E = "}"; // la fin d'un mot à extraire
public static final String PATH = "fichierCSH.txt"; // le nom du fichier par défaut lu

/* On peut passer un paramètre à la méthode main() :
  • le nom du fichier et s'il n'est pas spécifiée, on utilise PATH. * Cette méthode appelle d'abord extract() * puis split() et affiche les mots distincts trouvés */ public static void main(String[] args) { String path; if ( args.length>0 ) { path = args[0]; } else { path = PATH; } new Finally().traiterFichier(ZONE_B, ZONE_E, VALUE_B, VALUE_E, path); } public void traiterFichier(String zoneB, String zoneE, String valueB, String valueE, String filename) { String string = extract(filename, zoneB, zoneE); ArrayList<String> List = new ArrayList<String>(); if (string != null) { Collection<String> mots = split(string, valueB, valueE); for (String mot : mots) { //System.out.println(mot); } } else { System.out.println("Aucune chaine trouvée comprise entre " + zoneB + " et " + zoneE); } } /** * Lit le fichier spécifié et extrait la partie située entre ZONE_B et ZONE_E * @param filename nom du fichier * @return la chaîne extraite ou null si aucune chaîne trouvée, ou si le fichier n'existe pas */ private String extract(String filename, String ZONE_B, String ZONE_E) { try { StringBuilder stringBuilder = new StringBuilder(); BufferedReader buff = new BufferedReader(new FileReader(filename)); try { String line; while ((line = buff.readLine()) != null) { stringBuilder.append(line); stringBuilder.append('\n'); } } finally { buff.close(); } String toutLeFichier = stringBuilder.toString(); int a = toutLeFichier.indexOf(ZONE_B); int b = toutLeFichier.indexOf(ZONE_E); if (a >= 0 && b >= 0) { return toutLeFichier.substring(a + ZONE_B.length(), b); } } catch( FileNotFoundException e) { System.err.println("Fichier " + new File(filename).getAbsolutePath() + " introuvable"); } catch (IOException ioe) { System.err.println("Erreur --" + ioe.getMessage()); ioe.printStackTrace(); } return null; } /** * Extrait de la chaîne spécifiée la liste, sans doublons, des mots situés entre VALUE_B et VALUE_E * @param string la chaîne dont on doit extraire les mots * @return la liste de mots extraite */ private Collection<String> split(String string, String VALUE_B, String VALUE_E) { Collection<String> mots = new LinkedHashSet<>(); String[] tab = string.split("\n"); for (int i = 0; i < tab.length; i++) { //System.out.println(i + " : " + tab[i]); int index1 = tab[i].indexOf(VALUE_B); while (index1 >= 0) { int index2 = tab[i].indexOf(VALUE_E, index1); if (index2 >= 0) { int index3 = tab[i].lastIndexOf("{", index2); if (index3 != index1) { System.err.println("Problème dans le fichier : { non fermée en " + index1); } String x = tab[i].substring(index1 + 1, index2); mots.add(x); } else { System.err .println("Problème dans le fichier : { non fermée en " + index1); break; } index1 = tab[i].indexOf(VALUE_B, index2); } // fin de la boucle while } // fin de la boucle for return mots; } }

1 réponse

Bonjour,

Ceci devrai t'aider :

public JTextArea log;

// Fenêtre
public Console() {
    JFrame f = new JFrame("Console");
    log = new JTextArea();
    f.setSize(800, 600);  
    f.add(log);
    f.setVisible(true);
}

// Remplace System.out.printLn par prompt();
public void prompt(String msg) {
    log.append(msg + "\n");
}


Après tu adaptes avec tes dimensions et tailles de texte :)
1
khalous91 Messages postés 18 Date d'inscription mercredi 15 avril 2015 Statut Membre Dernière intervention 17 juin 2015
27 avril 2015 à 12:38
Merci MrYannKee ;)

J'ai essayer ton code et c'est presque parfait ^^
J'ai juste un petit problème lorsque j'appuie sur OK j'ai bien la fenetre qui s'ouvre avec le Jtextarea mais il n'y a rien dedans...

je te passe mes codes source, si tu as le temps jette y un coup d'oeil :

code console :

import java.util.Collection;

import javax.swing.JFrame;
import javax.swing.JTextArea;


public class Console {

public Collection<String> Console() {
JFrame f = new JFrame("Console");
JTextArea res = new JTextArea();
f.setSize(300, 300);
f.add(res);
f.setVisible(true);

return null;
}

public JTextArea res;

public void prompt(String mot) {
res.append(mot + "\n");
}
}


code SimpleFenetre :

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.Collection;
import java.util.LinkedHashSet;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextArea;


public class simplefenetre extends JFrame {

private JPanel contentPane;
private static JTextField zoneB;
private static JTextField valueE;
private static JTextField zoneE;
private static JTextField valueB;
private JTextField textField_4;



public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
simplefenetre frame = new simplefenetre();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

/* Le constructeur */

public simplefenetre() {
// On créer un groupe de boutons .
ButtonGroup groupeDeBoutons = new ButtonGroup();


setTitle("Traiter vos fichiers");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);

// Button "OK"
JButton btnOk = new JButton("OK");
btnOk.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// On lit les 5 champs

String ZONE_B = zoneB.getText();
String ZONE_E = zoneE.getText();
String VALUE_B = valueB.getText();
String VALUE_E = valueE.getText();
String PATH = textField_4.getText();
JTextArea res = new JTextArea();

// On appelle la méthode traiterFichier
Collection<String> a1 = new LinkedHashSet<>();
a1 = new Console().Console();

for (String mot : a1)
{
//affichage
System.out.println(mot);
res.append(mot + "\n");

}
}

});

// mise en relation du bouton ok avec les deux autres
groupeDeBoutons.add(btnOk);
btnOk.setBounds(243, 228, 58, 23);
contentPane.add(btnOk);

// Button "PARCOURIR"

JButton btnParcourir = new JButton("PARCOURIR");
btnParcourir.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
browseFile(); // sert au bouton PARCOURIR d'aller chercher un fichier x
}
});

// mise en relation du bouton PARCOURIR avec les deux autres
groupeDeBoutons.add(btnParcourir);
btnParcourir.setBounds(304, 56, 120, 23);
contentPane.add(btnParcourir);

// Button "ANNULER"

JButton btnAnnuler = new JButton("ANNULER");
btnAnnuler.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});

// mise en relation du bouton ANNULER avec les deux autres
groupeDeBoutons.add(btnAnnuler);
btnAnnuler.setBounds(311, 228, 113, 23);
contentPane.add(btnAnnuler);

// On créer les composants de saisies .

zoneB = new JTextField("#>");
zoneB.setBounds(116, 112, 86, 20);
contentPane.add(zoneB);
zoneB.setColumns(10);

zoneE = new JTextField("#<");
zoneE.setBounds(116, 145, 86, 20);
contentPane.add(zoneE);
zoneE.setColumns(10);

valueB = new JTextField("{");
valueB.setBounds(116, 176, 86, 20);
contentPane.add(valueB);
valueB.setColumns(10);

valueE = new JTextField("}");
valueE.setBounds(116, 207, 86, 20);
contentPane.add(valueE);
valueE.setColumns(10);


JLabel lblNewLabel = new JLabel("VALUE_B ");
lblNewLabel.setBounds(10, 179, 86, 14);
contentPane.add(lblNewLabel);

JLabel lblNewLabel_1 = new JLabel("ZONE_B");
lblNewLabel_1.setBounds(10, 115, 73, 14);
contentPane.add(lblNewLabel_1);

JLabel lblNewLabel_2 = new JLabel("VALUE_E");
lblNewLabel_2.setBounds(10, 210, 73, 14);
contentPane.add(lblNewLabel_2);

JLabel lblNewLabel_3 = new JLabel("ZONE_E");
lblNewLabel_3.setBounds(10, 148, 73, 14);
contentPane.add(lblNewLabel_3);

textField_4 = new JTextField();
textField_4.setBounds(10, 57, 192, 20);
contentPane.add(textField_4);
textField_4.setColumns(10);

}

private void browseFile() {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Choisir le fichier...");
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser.setMultiSelectionEnabled(false);
if ( !textField_4.getText().isEmpty() ) { // faire bien attention : bien faire correspondre notre textField choisi, ici le textField_4
fileChooser.setSelectedFile(new File(zoneB.getText()));
}
// il y a plein d'autres méthodes pour customiser le composant (filtre sur les fichiers par exemple) : voir doc.
if ( fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION ) {
textField_4.setText( fileChooser.getSelectedFile().getAbsolutePath().toString() );
}
}
}



code Finally :

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashSet;

public class Finally {


public static final String ZONE_B = "#>"; // le début de la sous partie de texte à extraire
public static final String ZONE_E = "#<"; // la fin de la sous partie de texte à extraire
public static final String VALUE_B = "{"; // le début d'un mot à extraire
public static final String VALUE_E = "}"; // la fin d'un mot à extraire
public static final String PATH = "fichierCSH.txt"; // le nom du fichier par défaut lu

/* On peut passer un paramètre à la méthode main() :
  • le nom du fichier et s'il n'est pas spécifiée, on utilise PATH. * Cette méthode appelle d'abord extract() * puis split() et affiche les mots distincts trouvés */ public static void main(String[] args) { String path; if ( args.length>0 ) { path = args[0]; } else { path = PATH; } new Finally().traiterFichier(ZONE_B, ZONE_E, VALUE_B, VALUE_E, path); } public Collection<String> traiterFichier(String zoneB, String zoneE, String valueB, String valueE, String filename) { String string = extract(filename, zoneB, zoneE); Collection<String> mots = new LinkedHashSet<>(); if (string != null) { mots = split(string, valueB, valueE); } else { System.out.println("Aucune chaine trouvée comprise entre " + zoneB + " et " + zoneE); } return mots; } /** * Lit le fichier spécifié et extrait la partie située entre ZONE_B et ZONE_E * @param filename nom du fichier * @return la chaîne extraite ou null si aucune chaîne trouvée, ou si le fichier n'existe pas */ private String extract(String filename, String ZONE_B, String ZONE_E) { try { StringBuilder stringBuilder = new StringBuilder(); BufferedReader buff = new BufferedReader(new FileReader(filename)); try { String line; while ((line = buff.readLine()) != null) { stringBuilder.append(line); stringBuilder.append('\n'); } } finally { buff.close(); } String toutLeFichier = stringBuilder.toString(); int a = toutLeFichier.indexOf(ZONE_B); int b = toutLeFichier.indexOf(ZONE_E); if (a >= 0 && b >= 0) { return toutLeFichier.substring(a + ZONE_B.length(), b); } } catch( FileNotFoundException e) { System.err.println("Fichier " + new File(filename).getAbsolutePath() + " introuvable"); } catch (IOException ioe) { System.err.println("Erreur --" + ioe.getMessage()); ioe.printStackTrace(); } return null; } /** * Extrait de la chaîne spécifiée la liste, sans doublons, des mots situés entre VALUE_B et VALUE_E * @param string la chaîne dont on doit extraire les mots * @return la liste de mots extraite */ private Collection<String> split(String string, String VALUE_B, String VALUE_E) { Collection<String> mots = new LinkedHashSet<>(); String[] tab = string.split("\n"); for (int i = 0; i < tab.length; i++) { //System.out.println(i + " : " + tab[i]); int index1 = tab[i].indexOf(VALUE_B); while (index1 >= 0) { int index2 = tab[i].indexOf(VALUE_E, index1); if (index2 >= 0) { int index3 = tab[i].lastIndexOf("{", index2); if (index3 != index1) { System.err .println("Problème dans le fichier : { non fermée en " + index1); } String x = tab[i].substring(index1 + 1, index2); mots.add(x); } else { System.err .println("Problème dans le fichier : { non fermée en " + index1); break; } index1 = tab[i].indexOf(VALUE_B, index2); } // fin de la boucle while } // fin de la boucle for return mots; } }


thinks ;)
0
Utilisateur anonyme
27 avril 2015 à 14:31
Salut, tu devrai utilise la méthode
prompt(String);
que je t'ai donné au dessus et là ça devrai marcher (au lieu de
res.append(String);
)
0
khalous91 Messages postés 18 Date d'inscription mercredi 15 avril 2015 Statut Membre Dernière intervention 17 juin 2015 > Utilisateur anonyme
27 avril 2015 à 14:46
Re, j'ai fais ce que tu m'as dit mais rien ne s'affiche sur la JTextArea....
0
Utilisateur anonyme
27 avril 2015 à 14:49
C'est bizarre... Là je vois pas où ça bloque désolé...
0
khalous91 Messages postés 18 Date d'inscription mercredi 15 avril 2015 Statut Membre Dernière intervention 17 juin 2015 > Utilisateur anonyme
27 avril 2015 à 14:56
arf c'est pas grave! merci MrYannKee ;)
0