2

I have a JList and I use a DefaultListModel to store the list entries. I have a button on that panel. When the button is clicked, I add new entry to DefaultListModel .

button actionPerformed:

My problem is, after I did the operation on my DefaultListModel, the content of JList doesn't change, I'm wondering that do I need to call a sort of refresh method on JList after I make changes on the ListModel?

public void actionPerformed(ActionEvent e) {
        ModifyXMLFile.create(FileList.listModel);
        FileList.fileList1.revalidate();
    }

JList Class:

public class FileList {
public static DefaultListModel listModel;
public static WebList fileList1 = null;
public static Component getGui(File[] all) {
    listModel = new DefaultListModel();
    for(File file:all){
      listModel.addElement(file);
    }
    final WebList fileList = new WebList(listModel);
    fileList1=fileList;
    fileList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    fileList.setCellRenderer(new FileRenderer(!vertical));

    fileList.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {


    });     
}
itro
  • 7,006
  • 27
  • 78
  • 121

2 Answers2

3

Try to call the method of DefaultListModel

protected void fireContentsChanged(Object source, int index0, int index1)
StanislavL
  • 56,971
  • 9
  • 68
  • 98
  • **I did add this**`listModel.fireContentsChanged(listModel, 0, listModel.size() -1);` **but i get this error in my code:** `fireContentsChanged has protected access in javax.swing.AbstractListModel` **How can i fix it?** – itro Mar 12 '12 at 09:06
  • @itro never, really never to call implemented methods in the XxxModel out of the XxxModel code, – mKorbel Mar 12 '12 at 09:09
  • When your model is changed you should let all listeners know about this. The method is protected so you should call it inside another model method or (worse case as mKorbel mentioned) make the method public. – StanislavL Mar 12 '12 at 11:56
3

1) remove code line panel.updateUI(); this code line is about Look And Feels

2) Swing is single threaded and updates to the Swing GUI must be done on EDT, otherwise contents or changes to the GUI are not visible or contents isn't refreshed or freeze

3) you have look at SwingWorker for loading JList's Item on the background task, then output from SwingWorker to the GUI will be done on EDT

mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • where should i apply swingWorker, in button actionPerformed or in JList class? – itro Mar 12 '12 at 09:18
  • right invoke SwingWorker from JButtons Action, create class, void or... declarations for JList accesible thought whole your code and cast DefaultListModel for current instace of JList inside SwingWorkers method publish() or done(), – mKorbel Mar 12 '12 at 09:29
  • [this SwingWorker example](http://stackoverflow.com/a/6114890/714968) could help you with that – mKorbel Mar 12 '12 at 09:32