Reputation: 1
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
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
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