views:

123

answers:

1

the issue i mentioned in this post is actually happening because of cross threading GUI issues (i hope).

could you help me with Java version of action delegate please?

in C# it is done as this inline:

        this.Invoke(new Action(delegate()
        {...}));

how is this achived in Java?

thank you.

public class processChatMessage implements Observer {

    public void update(Observable o, Object obj) {


        System.out.println("class class class" + obj.getClass());

        if (obj instanceof String){

            String msg = (String)obj;

            formatChatHeader(chatHeader.Away, msg);

            jlStatusBar.setText("Message Received");

            // Show chat form
            setVisibility();

        }
    }
}

processChatMessage is invoked by a separate thread triggered by receiving new data from a remote node.

and i think the error is being produced as it trying to update GUI controls.

do you think this is the reason? i ask because im new to Java and C#, but this is what is going on i think.

SOLUTION:

public class processChatMessage implements Observer {

    public void update(Observable o, Object obj) {

        if (obj instanceof String){

            final String msg = (String)obj;

            try {

                SwingUtilities.invokeAndWait(new Runnable( ) {

                    public void run( ) {

                        formatChatHeader(chatHeader.Away, msg);
                        jlStatusBar.setText("Message Received");
                        setVisibility();
                    }
                });
            } catch (InterruptedException e){

            } catch (InvocationTargetException e){

            }
        }
    }
}
+3  A: 

The nearest equivalent would probably be the Runnable interface - basically a single-method interface with a method taking no parameters and returning no value. You can use an anonymous inner class to achieve an effect something like anonymous methods:

executeRunnable(new Runnable() {
    public void run() {
        // Do stuff here
    }
});

Yes, it's a bit verbose... but hopefully Java 7 closures will come to the rescue, eventually :)

Now, that's the general idea of the Action delegate. In this particular instance you should look at SwingUtilities.invokeLater(Runnable) and SwingUtilities.invokeAndWait(Runnable) as the rough equivalent of Control.BeginInvoke and Control.Invoke respectively.

Jon Skeet
@Jon: thanks for the tip now it works without throwing exceptions as reported in the previous post.
iEisenhower