简体   繁体   中英

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?

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.

ie,

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.

That is happening because of this:

DefaultListModel model;
model = new DefaultListModel();

every time you execute this lines, you create a new object, so the old information in the list is gone,

instead initialize the model in the constructor and use the jButton1ActionPerformed only for adding the elements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM