Search code examples
javastringswingjlistdefaultlistmodel

Java updating listmodel string


I have a JList that uses a list model to add strings of text to the JList. I am having trouble figuring out how to update a selected listModel. I am able to select the listModel String (I have verified that what ever I select returns correctly) but I am unable to figure out how to update the listModel string I select. Any help with this would be greatly appreciated. Is there a updateElement(variable) or something I could use to accomplish this?

    String string1 = "hello";
    String string2 = "goodbye";
        String myItem = jlst.getSelectedValue();
    // myItem is the string returned
        listModel.addElement(string1 + string2);
// adds a new element is there anyway to update myItem so string1 and string 2 become apart of the myItem string ?

Solution

  • Make sure you are using a DefaultListModel.

    /* Create model */        
    DefaultListModel<String> dlm = new DefaultListModel<>();
    
    /* Add elements */ 
    dlm.addElement("test");
    dlm.addElement("test2");
    
    /* JList to use the model */ 
    JList<String> list = new JList<>(dlm);
    
    /* Update an element */
    dlm.set(1, "test3");