user2491325
user2491325

Reputation: 1

Using a textbox for input for a JList

Okay I know this has got to be something very simple I am trying to do but I am pulling my hair out trying to figure it out. I have a GUI with three text boxes and one JList I am trying to add to the list. Here is my addButton code below:

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

    String emailText = custEmailTextBox.getText();
    String firstText = firstNameTextBox.getText();
    String lastText = lastNameTextBox.getText();

    DefaultListModel<String> model = new DefaultListModel<>();

    model.addElement(firstText + "  :  " + lastText + "  :  " + emailText);
    custList.setModel(model);   

}

I can add text to my list but if I try to add a second line of text it just overwrites the first one. How can I just add to the list with out overwriting the other?

Upvotes: 0

Views: 1689

Answers (2)

Vishal K
Vishal K

Reputation: 13066

I can add text to my jlist box but if I try to add a second line of text it just overwrites the first one.

Because, each time your are adding a text to JList you are creating new DefaultListModel and setting that model to the JList which removes the already added texts in JList. To overcome this problem create the object of DefaultListModel once outside the addButtonActionPerformed method.Also set the model for JList once. Your code should be something like this:

DefaultListModel<String> model = new DefaultListModel<>();
private void someMethod() //call this method in your constructor or method where you have initialized your GUI
{
    custList.setModel(model); 
}
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {    

    String emailText = custEmailTextBox.getText();
    String firstText = firstNameTextBox.getText();
    String lastText = lastNameTextBox.getText();
    model.addElement(firstText + "  :  " + lastText + "  :  " + emailText);
}

Upvotes: 2

rimero
rimero

Reputation: 2383

By default a JList will use a DefaultListModel.

Cast the JList model via list.getModel(), and just remove your setModel method call which resets the list data.

Upvotes: 1

Related Questions