Pink Flying Elephant
Pink Flying Elephant

Reputation: 151

JList of all Filenames in a Folder

I'm trying to program a que card application using Swing. Now I'm trying to list all the que card decks (which are txt files) in one folder in a JList. So I want to get the filenames of the text files and add them to the list, which I've already created. I tried multiple approaches and this is the closest I think I've gotten:

    JList<DeckTypeA> listTypeADecks = new JList();
    DefaultListModel<DeckTypeA> listModelTypeADecks = new DefaultListModel<DeckTypeA>();
    File folder = new File("dexA");


//much later in the code
    File[] listOfFiles = folder.listFiles();
    for (int i = 0; i < listOfFiles.length; i++) {
          if (listOfFiles[i].isFile()) {
            String[] listOfFileNames = new String[listOfFiles.length];
            listOfFileNames[i] = listOfFiles[i].getName();
            listTypeADecks.setListData(listOfFileNames); //here i get an error
          };

I get an error message saying that JList.setListData(String[]) is invalid (I've tried adding it to the default list model and adding it in many different other ways). When I looked up the method it always said that the parameter has to be an object but isn't a string a type of object? Help would be much appreciated and if you notice anything other mistakes please let me know.

Upvotes: 1

Views: 869

Answers (1)

Sven
Sven

Reputation: 2889

There are a few issues with your code.

  • You're declaring listofFileNames inside the for-loop. This variable is initialized every loop again and destroyed at the end. This means any changes are thrown away.

  • You're calling listTypeADecks.setListData at the end of each loop, but you probably want to call it after the whole loop when it's complete.

  • In your implementation there will be empty Strings in listOfFileNames since not every index may be a file, but you just skip them.

You probably want something like this:

    File[] listOfFiles = folder.listFiles();
    List<String> listOfFileNames = new List<String>();
    for (int i = 0; i < listOfFiles.length; i++) {
          if (listOfFiles[i].isFile()) {
            listOfFileNames.add(listOfFiles[i].getName());
          };
    listTypeADecks.setListData(listOfFileNames.toArray());

Upvotes: 2

Related Questions