Java Swing How to - Add String value to DefaultListModel








Question

We would like to know how to add String value to DefaultListModel.

Answer

import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
/*from  ww w  . ja v a 2s . com*/
public class Main {

  public static void main(String[] args) {
    JFrame f = new JFrame();
    DefaultListModel<String> dlm = new DefaultListModel();
    String[] modelElems = { "Apple", "Orange", "Banana" };
    for (int i = 0; i < modelElems.length; i++)
      dlm.add(i, modelElems[i]);

    JList<String> lstFruitList = new JList(dlm);
    lstFruitList.setVisible(true);

    JPanel p = new JPanel();
    p.add(lstFruitList);
    f.add(p);
    f.setLocation(0, 0);
    f.setSize(400, 400);
    f.setVisible(true);
  }
}