Take the result of a list and print it in a JTextArea

1

my method "finderEnTextArea" , it does not work, it only prints the last string that says Fin, not the list of files. When I select the folder, and supposedly in the method searchTextArea I list all the files contained in it and I print them in a JTextArea, the results do not come out in the JTextArea. Only print the last order.

Usage:

  

eclipse Oxygen 64bits

     

java 1.8.

Does someone detect where I have the error? Maybe the mistake is easy, but I'm starting with java and any help is welcome. Thanks.

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import javax.swing.*;

public class VentanaPreguntaPrimera extends JFrame {

    private JPanel contentPane;
    private JTextField textFieldPlaylist;
    private JTextField textFieldCarpeta;
    private JTextArea textArea;
    private Fichero fichero; 
    private Carpeta carpeta; 
    private String tituloVentana = "H#02 - lista de ficheros en carpeta";

    public Fichero getFichero() {
        return fichero;
    }

    public void setFichero(Fichero fichero) {
        this.fichero = fichero;
    }

    public Carpeta getCarpeta() {
        return carpeta;
    }

    public void setCarpeta(Carpeta carpeta) {
        this.carpeta = carpeta;
    }

    public JTextField getTextFieldPlaylist() {
        return textFieldPlaylist;
    }

    public void setTextFieldPlaylist(JTextField textFieldPlaylist) {
        this.textFieldPlaylist = textFieldPlaylist;
    }

    public JTextField getTextFieldCarpeta() {
        return textFieldCarpeta;
    }

    public void setTextFieldCarpeta(JTextField textFieldCarpeta) {
        this.textFieldCarpeta = textFieldCarpeta;
    }

    public JTextArea getTextArea() {
        return textArea;
    }

    public void setTextArea(JTextArea textArea) {
        this.textArea = textArea;
    }


    public VentanaPreguntaPrimera() {

        // Parametros asociados a la ventana
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 850, 340);
        contentPane = new JPanel();
        contentPane.setLayout(null);
        setContentPane(contentPane);
        setTitle(tituloVentana); // titulo de la ventana que saco


        textFieldPlaylist = new JTextField();
        textFieldPlaylist.setToolTipText("Inserta la ruta del ficherot");
        // el de arriba
        textFieldPlaylist.setBounds(52, 26, 609, 20);
        contentPane.add(textFieldPlaylist);
        textFieldPlaylist.setColumns(10);

        /* JTextField que es el campo de la ruta de la carpeta */
        textFieldCarpeta = new JTextField();
        textFieldCarpeta.setToolTipText("Inserta la ruta de la carpeta");
        // el de abajo
        textFieldCarpeta.setBounds(52, 250, 609, 20);
        contentPane.add(textFieldCarpeta);
        textFieldCarpeta.setColumns(10);

        // boton del playlist
        JButton btnSeleccionar = new JButton("fichero ?");
        btnSeleccionar.setBounds(688, 25, 109, 23);
        contentPane.add(btnSeleccionar);

        // boton de la carpeta
        JButton btnSeleccionarCarpeta = new JButton("CARPETA ?");
        btnSeleccionarCarpeta.setBounds(688, 250, 109, 23);
        contentPane.add(btnSeleccionarCarpeta);


        textArea = new JTextArea();
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        textArea.setBounds(52, 76, 760, 156);

        JScrollPane scroll = new JScrollPane(textArea);
        scroll.setBounds(52, 76, 760, 156);
        contentPane.add(scroll);

        // boton del playlist su ActionListener
        btnSeleccionar.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                /*
                 * una vez pulsa el boton, llamo al metodo que saca una ventana de busqueda del
                 * archivo
                 */
                creaVentanaElegirFichero();
            }
        });

        // boton del buscar carpeta su ActionListener
        btnSeleccionarCarpeta.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                /*
                 * una vez pulsa el boton, llamo al metodo que saca una ventana de busqueda del
                 * archivo
                 */
                creaVentanaElegirCarpeta();
            }
        });

    }

    /* metodo que saca una ventana de busqueda de archivo */
    public void creaVentanaElegirFichero() {

        JFileChooser fc = new JFileChooser();
        fc.setCurrentDirectory(new File("c:/p"));

        int seleccion = fc.showOpenDialog(contentPane);

        // Si el usuario, pincha en aceptar
        if (seleccion == JFileChooser.APPROVE_OPTION) {

            File ficheroTemporal = fc.getSelectedFile();

            fichero = new Fichero(ficheroTemporal);

            // Escribe la ruta del fichero seleccionado en el campo de texto
            textFieldPlaylist.setText(fichero.getFichero().getAbsolutePath());


            try (FileReader fr = new FileReader(fichero.getFichero())) {
                String cadena = "";
                int valor = fr.read();
                while (valor != -1) {
                    cadena = cadena + (char) valor;
                    valor = fr.read();
                }
                textArea.setText(cadena); // aqui lo imprime en TextArea
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

    /* metodo que saca ventana de busqueda de archivos en directorio */
    public void creaVentanaElegirCarpeta() {


        JFileChooser fc = new JFileChooser();
        fc.setCurrentDirectory(new File("c:/p"));
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int seleccion = fc.showOpenDialog(contentPane);

        if (seleccion == JFileChooser.APPROVE_OPTION) {

            File carpetaTemporal;
            carpetaTemporal = fc.getSelectedFile();
            carpeta = new Carpeta(carpetaTemporal);

            // Escribe la ruta del fichero seleccionado en textField
            textFieldCarpeta.setText(carpeta.getCarpeta().getAbsolutePath());

            // este si funciona, me lo saca por consola
            carpeta.buscador(carpeta.getCarpeta().getAbsolutePath());

            // ahora pruebo a sacarlos al JTextArea - NO FUNCIONA!
            carpeta.buscadorEnTextArea(carpeta.getCarpeta().getAbsolutePath(), textArea);
        }
    }

}



/*
 * clase donde meto la ruta o carpeta donde buscar y hace operaciones
 */

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import javax.swing.JTextArea;

public class Carpeta {

    public File carpeta; // carpeta donde busco

    public File getCarpeta() {
        return carpeta;
    }

    public void setCarpeta(File carpeta) {
        this.carpeta = carpeta;
    }

    // constructor por defecto
    public Carpeta() {
    }

    public Carpeta(File carpeta) {
        this.carpeta = carpeta;
    }


    public void buscador(String queCarpeta) {

        String path = queCarpeta;

        String files;
        File folder = new File(path);
        File[] listOfFiles = folder.listFiles();

        for (int i = 0; i < listOfFiles.length; i++) {

            if (listOfFiles[i].isFile()) {
                files = listOfFiles[i].getName();
                if (files.endsWith(".txt") || files.endsWith(".TXT")) {
                    System.out.println(files);
                }
            }
        }
        System.out.println("Fin");
    }


    public void buscadorEnTextArea(String queCarpeta, JTextArea textArea) {

        // Aquí la carpeta que queremos explorar, por ejemplo:
        String path = queCarpeta;

        String files;
        File folder = new File(path);
        File[] listOfFiles = folder.listFiles();

        for (int i = 0; i < listOfFiles.length; i++) {

            if (listOfFiles[i].isFile()) {
                files = listOfFiles[i].getName();
                if (files.endsWith(".txt") || files.endsWith(".TXT")) {
                    textArea.setText(files); // aqui lo imprime en TextArea... PERO NO FUNCIONA
                }
            }
        }
        textArea.setText("Fin"); // le añado fin - Este si funciona
    }
}
    
asked by tuxero 21.09.2017 в 16:40
source

1 answer

0

It is that by doing this in the loop: textArea.setText(files); in each iteration will replace the file names. You must concatenate in a variable, for example, a Stringbuilder and then, outside the loop, print all the names of files collected within the loop.

If the word Fin should also go to the end of the file names, you should include it within the variable sb .

It is that when you make setText you delete the content that is in the TextField, replacing it with the current value.

For example:

StringBuilder sb = new StringBuilder();

for (int i = 0; i < listOfFiles.length; i++) {

        if (listOfFiles[i].isFile()) {
            files = listOfFiles[i].getName();
            if (files.endsWith(".txt") || files.endsWith(".TXT")) {
                sb.append(files); 
                sb.append(System.lineSeparator()); //Salto de línea 

            }
        }
    }
//Fin también debe incluirse en el sb, si quieres que aparezca al final.
sb.append("Fin");

//Imprimes todos los archivos dentro del StringBuilder 
textArea.setText(sb.toString()); 
    
answered by 21.09.2017 / 16:56
source