3

I know this isn't the only question about filling JLists, but I didn't find the answer in another SO thread.

I've used the Netbeans GUI builder to create my GUI. The JList is added to a scrollpane, if I hardcode the content of the JList everything is showed fine.

jList1.setModel(new javax.swing.AbstractListModel() { 
public String[] strings = {"1", "2", "etc..."}; 
@Override 
  public int getSize() { 
  return strings.length; 
} 

@Override 
   public Object getElementAt(int i) { 
   return strings[i]; 
} 
}); 

But if I try to add items dynamically via SwingWorker, nothing appears.

JList jList1 = new javax.swing.JList();
DefaultListModel info = new DefaultListModel();
....
jList1.setModel(info);

....
public void FillList(final String subject) {

    worker = new SwingWorker() {
        @Override
        protected Object doInBackground() {
            info.addElement(subject);

            return 0;
        }

        @Override
        protected void done() {
        }
    };
    worker.execute();
}

I just want to show the subjects in the JList for visual purposes, the rest is done in the background.

Any help is appreciated,

Thanks!

Jef
  • 791
  • 1
  • 18
  • 36
  • Are you sure the code is executing? A little debuggin or even a `System.out.println` well placed can give a lot of perspective. – SJuan76 Oct 05 '12 at 10:45
  • Thanks for your answer. Yes I am sure it is executing. If place this line: `System.out.println(info.getSize());` in `doInBackground()` the size of the `ListModel` increments. – Jef Oct 05 '12 at 10:49
  • When you use dynamic content, are you storing the dynamic content in the array "strings"? – Clark Oct 05 '12 at 10:54
  • Oops I forgot to change the `getSize()` and `getElementAt()` methods. But in another class I retrieve certain messages from an e-mail account, from which I take the subject and call `FillList(subject)` so FillList gets called for every e-mail. I just want to show the subjects in the JList for visual purposes, the rest is done in the background. – Jef Oct 05 '12 at 11:01
  • 1
    **WRONG** - you _must not_ change a component (neither any of its properties nor the underlying model) from the worker thread, that is **NOT** in doInBackground() – kleopatra Oct 05 '12 at 11:02

1 Answers1

3
Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • Thanks for your answer! Going to put some time in reading those links, thanks for your help. – Jef Oct 05 '12 at 11:03