0

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 ?

2 Answers 2

3

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");
Sign up to request clarification or add additional context in comments.

Comments

2

I am having trouble figuring out how to update a selected listmodel.

Read the section from the Swing tutorial on How to Use Lists. It has a working example that shows you how to dynamically add/remove elements from the DefaultListModel based on a user interaction with the GUI.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.