Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear a JList in Java?

i have a jList in gui where i can add some data with Add button. what i want to add another button called Clear which will clear all elements. i tried this:

private void jButtonClearActionPerfomed(java.awt.event.ActionEvent evt)
{
    DefaultListModel listmodel=new DefaultListModel();
    jList1 = new JList(listmodel);
    if(evt.getSource()==jButtonClear) JList.setListData(new String[0];
    else listmodel.removeAllElements();
}

When I click on Add button this will add elements.

When I click on Clear button this remove elements.

But when I re-click on Add button, there is nothing in the jList1

like image 990
Pan24112012 Avatar asked Nov 28 '12 04:11

Pan24112012


People also ask

What is DefaultListModel in Java?

DefaultListModel provides a simple implementation of a list model, which can be used to manage items displayed by a JList control. For more information, see JList Class. Constructor.

How do I add an item to a JList?

Show activity on this post. Populate the JList with a DefaultListModel, not a vector, and have the model visible in the class. Then simply call addElement on the list model to add items to it.


1 Answers

You should not be reinitializing the entire JList widget just to remove some items from it. Instead you should be manipulating the lists model, since changes to it are 'automatically' synchronized back to the UI. Assuming that you are indeed using the DefaultListModel, this is sufficient to implement your 'Clear All' functionality:

private void jButtonClearActionPerfomed(java.awt.event.ActionEvent evt) {
    if(evt.getSource()==jButtonClear) {
        DefaultListModel listModel = (DefaultListModel) jList1.getModel();
        listModel.removeAllElements();
    }
}
like image 85
Perception Avatar answered Sep 29 '22 10:09

Perception