Wednesday, June 26, 2013

Adding and removing elements from list during runtime


By default List don’t support methods to add/remove elements from list

Why ???
At the time of creation of List jList creates a ListModel object which stores
data of list and it does not support runtime addition or deletion of objects
For adding elements at runtime you need to change ListModel to DefaultListModel
How to do that ?
Here are the steps to do it.
·         Add a List to your Form
·         Right click on List and Select Properties
·         Now look for Model Property
·         Click ellipsis( button that look like [..]) which is in front of model property
·         Now a dialog box will open
·         Now select custom Code from Combobutton
·         And type code new DefaultListModel()  in the TextField. And click OK
·         Now Open Source Code

To desired event or method write the code

   //Getting ListModel in DefaultListModel
   DefaultListModel  dList = (DefaultListModel) list.getmodel();
//You can add Elements in list in two ways
// 1st : adding item at the end of list
dList.addelement(“new item”);
//2nd : Adding eelement at a specific index
dList.add(0,”new Item”);
//here 0 is the index
//to remove any element
dList.removeElementAt(index no);
//OR
dList.removeElement(“Element x”);

No comments:

Post a Comment