husin.anti husin.anti - 2 months ago 8
Java Question

How to add multiple line from TextField to JList

I have the following code :

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Tname = name.getText();

DefaultListModel model;
model = new DefaultListModel();
model.addElement(Tname);
list.setModel(model);
}


When I try this code, and add text from TextField, and show in Jlist,
it always replace previous line with new one.

How can I add multiple line without replacing previous input?

Answer

You're creating a new DefaultListModel every time this method is called, and so you're removing all data held by the original list model. The solution is not to do this. Get the current ListModel from your JList, don't create a new one, and then add your element to the current ListModel. That's it.

i.e.,

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // Tname       =   name.getText(); // *** follow Java naming rules please
    String tName = name.getText();

    DefaultListModel model = (DefaultListModel) list.getModel();
    model.addElement(tName);
}

Don't call setModel(...) when you do this since you're already using the current model.

Comments