Add element in Jlist

Asked

Viewed 496 times

-1

This one-button action serves to add the path of a file into 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 a second time and so it goes to the else:

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 1 > 0
  • Please provide a [mcve] so that it is possible to execute the code and test the problem.

  • Why not remove this if/Else and let java take care of the list size for you using modelo.addElement(l)?

1 answer

0

There are two problems here:

  • The first is your variable index be used this way. You do not need this variable, just use the method addElement(E). And you don’t need that if.

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

Also, I recommend you to use generic types properly.

To fix these problems, first declare the JList thus:

private JList<String> tListaArquivo;

And if possible, in the constructor of the class that has the method bArquivoActionPerformed or somewhere else that sets up the 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 variable index.

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 greatly. So instead of bArquivoActionPerformed, use botaoArquivoActionPerformed. Instead of tArquivo, use textBoxArquivo.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.