Add element in JList

-1

This action of a button is to add the path of a file to a JList :

 private void bArquivoActionPerformed(java.awt.event.ActionEvent evt) {                                         

    JFileChooser fileChooser = new JFileChooser();
    fileChooser.showOpenDialog(this);
    File arquivo = fileChooser.getSelectedFile();
    listaarquivos.add(arquivo);
    tArquivo.setText(arquivo.getPath());
    DefaultListModel modelo = new DefaultListModel();
    tListaArquivo.setModel(modelo);
    String l = arquivo.getPath(); 
    if(listaarquivos.size()==1){
        modelo.add(0,l);
        index = 1;
    }else{
        modelo.add(index, l);
        index++;
    }
}     

It shows the following error when the button is called the second time and so it goes to else :

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 1 > 0
    
asked by anonymous 19.12.2017 / 00:32

1 answer

0

There are two issues here:

  • The first is your index variable to be used this way. You do not need this variable, just use the addElement(E) . And you also do not need this if .

  • The second is that you are always creating a new DefaultListModel instead of using the existing one.

In addition, I recommend that you use the generic types appropriately.

To fix these problems, first declare JList like this:

private JList<String> tListaArquivo;

And if possible, in the constructor of the class that has method bArquivoActionPerformed or somewhere else that sets JList created, put this:

tListaArquivo.setModel(new DefaultListModel<>());

And then, try this:

private void bArquivoActionPerformed(java.awt.event.ActionEvent evt) {
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.showOpenDialog(this);
    File arquivo = fileChooser.getSelectedFile();
    listaarquivos.add(arquivo);
    DefaultListModel<String> modelo = tListaArquivo.getModel();
    tArquivo.setText(arquivo.getPath());
    modelo.addElement(arquivo.getPath());
}

Also delete your index variable.

Finally, the use of Hungarian notation is not recommended. Hungarian notation is the practice of prefixing variable names with information about the type or context in which it is declared, something that Java code conventions discourage. So, instead of bArquivoActionPerformed , use botaoArquivoActionPerformed . Instead of tArquivo , use textBoxArquivo .

    
20.12.2017 / 05:05