Kerry Kerry - 1 year ago 76
Java Question

Is This Bad Programming Practice

Please consider the following code:

public class MyClass extends javax.swing.JFrame {

private JTree jTree;
//Code ommited for clarity

public void methodCalledByAnotherThread(){

final DefaultTreeModel t = new DefaultTreeModel();
//Do some thing with t

SwingUtilities.invokeLater(new Runnable(){
public void Run(){

is created and executed on the Swing thread. Some time during its execution it starts a second thread which will eventually call the
. Not this method will NEVER be called on the Swing thread.

creates a (local)
object and does some work with it but because this is NOT on the Swing thread it cannot set the model into
hence the call to
. In the Runnable object , which is executed on the Swing thread, it sets the LOCAL
t into the

My question is (and I haven't actually compiled and run this code yet so it may not work).. is the above BAD programming practice? If so how can I set a
created on a NON-Swing thread into a Swing object?

Answer Source

That looks fine (in fact its the best way to do it). So long as //Do some thing with t does not include any elements that are already displayed on the UI.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download