How to clear a JList in Java?

Pan24112012 picture Pan24112012 · Nov 28, 2012 · Viewed 59.3k times · Source

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

Answer

Perception picture Perception · Nov 28, 2012

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();
    }
}