Path: csiph.com!usenet.pasdenom.info!weretis.net!feeder4.news.weretis.net!news.musoftware.de!wum.musoftware.de!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: Nigel Wade Newsgroups: comp.lang.java.help Subject: Re: Need simple example of how to safely pass data from worker to EDT swing threads. Date: Thu, 06 Dec 2012 17:27:22 +0000 Lines: 35 Message-ID: References: <118db2e0-86dc-4d6b-aabb-ba68ee8c2f53@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit X-Trace: individual.net XP8phZOBVS5no4dpEXByDg1dikmeDG1yZzZnj6SBx+VGO0a9Ylsd+YZeJSG3qLSeBQ Cancel-Lock: sha1:+T2xExKhxXa8IGLIvP+ElmR3Zmk= User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:12.0) Gecko/20120421 Thunderbird/12.0 In-Reply-To: <118db2e0-86dc-4d6b-aabb-ba68ee8c2f53@googlegroups.com> Xref: csiph.com comp.lang.java.help:2338 On 06/12/12 15:07, kwiateks@gmail.com wrote: > Hello Kinds Sirs, > > I need a simple runnable example of a swing application that has a GUI with a jcombobox filled with a long list of name/value objects (eg 3000 employee names and numbers). There is also a worker process that reads in a record from a file/database, and then updates the gui jcombo box so that the employee item is "selected". > > I was able to write something using java map and employee objects to set the selected item in the jcombo box, but if I invoke setSelectedItem in the worker thread, I get odd results/delays. > > See below snippets... how should the worker thread pass the employee object back to the gui for it to setSelectedItem? > .... > empBuffer= new Employee(id, lastName ); > map.put(empBuffer.getId()+"",empBuffer ); > model.addAll(map.values()); > Collections.sort(model); > myComboBox1.setModel(new javax.swing.DefaultComboBoxModel(model)); > .... > emp = (Employee) map.get(myData.getEmployeeNum()); > myComboBox1.setSelectedItem(emp); Use SwingWorker and its publish()/process() and done() methods. Use publish() in the background thread to add each element to a list of objects to be processed by process(). In process() (which runs on the EDT) add the elements to the JComboBox model. In done() select the element you want in the JComboBox model. http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html Although this may not solve the problem you were previously having, which is most likely caused by having too many objects in the JComboBox. You will still have the same number of objects in the JComboBox when SwingWorker.done() is completed. When you open the JComboBox the EDT has to render all 3000 objects into the popup list.