1

I have a DefautListModel which reads file names from a directory. Whenever I have more than 19 files I get:

java.lang.ArrayIndexOutOfBoundsException: Index 20 out of bounds for length 20

I tried ensureCapacity() for the listModel. I tried setVisibleRowCount() for the Jlist

Any suggestions?

    // get the file list
    String[] newList = getFileList();
    // create a list model
    listModel = new DefaultListModel<>();
    listModel.ensureCapacity( 1000 );
    for (String s : newList) {
      listModel.addElement(s);
    }

    // add the model to the jlist
    recipeList = new JList(listModel);
    recipeList.setName( "recipes" );
    recipeList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
    recipeList.setLayoutOrientation(javax.swing.JList.VERTICAL);
    recipeList.setVisibleRowCount( recipeList.getModel().getSize() );
    JScrollPane toScroll = new JScrollPane( recipeList,
            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
            JScrollPane.HORIZONTAL_SCROLLBAR_NEVER );
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
rasweeny
  • 11
  • 3
  • 2
    Where does the exception occur? – QBrute Jun 21 '19 at 13:43
  • Chances are, that somewhere in **your** code, you compute an invalid index, and use that. So, look carefully at the stack trace, and identify how/where **your** code shows up in that stack trace. I would be really really surprised if you found a bug in the java listmodel or jlist implementation. It is much more likely that some code of yours is "off by one", thus leading to this exception. – GhostCat Jun 21 '19 at 13:52
  • I know what causes a arrayIndexOutOfBounds. The exception occurs when reading the file names in after 19 files have been added to the directory – rasweeny Jun 21 '19 at 14:06
  • DefaultListModel is initiated without any size. I thought it would read the files in the directory and that would set the size. – rasweeny Jun 21 '19 at 14:12
  • You were right. I set the size for fileList to 20. I could only read in 20 files. – rasweeny Jun 21 '19 at 14:31
  • @rasweeny What caused the error – Pie Jun 21 '19 at 16:28

0 Answers0