Search code examples
javaswingjlistjtextareadefaultlistmodel

adding elements from jtextarea to jlist by clicking on jbutton


i have a jtextfield where i can add an element and by clicking on a button i want to add it to the jlist, now the problem i am having is that by clicking on the button it will add the element i want but when i add another element to the list the old one is gone and a new one appears in it's place. here is the code i have:

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

    DefaultListModel  model1= new DefaultListModel();

    model1.addElement(desc.getText());
    jList2.setModel(model1);
    jList2.setSelectedIndex(0);
    desc.setText("");
} 

can anyone help me with that? Thank you


Solution

  • Each time the button is clicked you are creating a new DefaultListModel and adding the element to this brand new list. Therefore you cannot add them all into the same list.

    Instead define your DefaultListModel model1 outside of addActionPerformed method and use the reference to the object inside like the following:

    DefaultListModel  model1= new DefaultListModel();
    
    private void addActionPerformed(java.awt.event.ActionEvent evt) {                                     
          model1.addElement(desc.getText());
          jList2.setModel(model1);
          jList2.setSelectedIndex(0);
          desc.setText("");
    
    }