Error in code for popular JList with file names of a folder

0

I can not pass a method to get the name of the files in a folder.

I have the following code:

inicializar.addWindowListener(new WindowListener(){
       @Override
       public void windowOpened(WindowEvent arg0){

            DefaultListModel dlm = new DefaultListModel();
            JList lstvRel = new JList();
            lstvRel.setModel(dlm);
            ListarArquivos l = new ListarArquivos();
            dlm = l.listar(); //Erro nesta linha!!
            for(int i = 0; i < l.listar().size(); i++){
                lstvRel.getModel().getElementAt(i).toString();                    
            }    

        }

And the class:

public class ListarArquivos {


    public void listar() {

        File dirArquivos = new File("C:\Users\lbell\Desktop\Turbo - teste");

        File[] Arquivos = dirArquivos.listFiles((File b) -> b.getName().endsWith(".xls") ||
                    b.getName().endsWith(".xlsx") ||
                    b.getName().endsWith(".xlsm") ||
                    b.getName().endsWith(".xlsb") ||
                    b.getName().endsWith(".ppt"));
    }

}
    
asked by anonymous 29.06.2016 / 07:18

1 answer

1

If your goal is to "populate a JList by starting the program.", the implementation is a bit different.

There are several ways to do this, using the methods you have already defined, to do the following:

In the class of your ' initialize ' object, you must create and add elements in your DefaultListModel dlm in the constructor and put it in your JList. A small example:

class Inicializar {

   JList lstRel;

   Inicializar(String dir) {

     // Cria a DefaultListModel
     DefaultListModel<String> dlm = new DefaultListModel<String>();

     // Cria a array de arquivos do diretorio
     File[] arquivos = (new File(dir)).listFiles((File b) -> b.getName().endsWith(".xls") ||
                b.getName().endsWith(".xlsx") ||
                b.getName().endsWith(".xlsm") ||
                b.getName().endsWith(".xlsb") ||
                b.getName().endsWith(".ppt"));

     // Adiciona os arquivos na DefaultListModel
     for(int i=0; i < arquivos.length; i++)
       addElement(arquivos[i].getName());

     // Coloca sua dlm em uma JList
     JList lstvRel = new JList(dlm);

   } 

   public JList getList() {

     return lstvRel;

  }

}
    
29.06.2016 / 18:16