Question

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

Was it helpful?

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("");

} 

OTHER TIPS

You are replacing the JList model every time you click the JButton. Instead you could use a single DefaultListModel at class level at startup and add to that.

    listModel = new DefaultListModel();
    listModel.addElement("Jane Doe");
    listModel.addElement("John Smith");
    listModel.addElement("Kathy Green");


    list = new JList(listModel);
public void actionPerformed(ActionEvent e) {
    int index = list.getSelectedIndex();
    listModel.remove(index);

    int size = listModel.getSize();

    if (size == 0) { //Nobody's left, disable firing.
        fireButton.setEnabled(false);

    } else { //Select an index.
        if (index == listModel.getSize()) {
            //removed item in last position
            index--;
        }

        list.setSelectedIndex(index);
        list.ensureIndexIsVisible(index);
    }
}
// Only once (may be in constructor),
// don't put this code in ActionListener method actionPerformed().
DefaultListModel model1 = new DefaultListModel(); 

Remaining code as it is.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top