Java C#操作委托的invokeAndWait [英] Java invokeAndWait of C# Action Delegate
问题描述
我在这篇文章中提到的问题实际上是由于跨线程GUI问题而发生的(我希望).
the issue i mentioned in this post is actually happening because of cross threading GUI issues (i hope).
您能帮我使用Java版本的动作委托吗?
could you help me with Java version of action delegate please?
在C#中是通过以下内联方式完成的:
in C# it is done as this inline:
this.Invoke(new Action(delegate()
{...}));
这在Java中是如何实现的?
how is this achived in Java?
谢谢.
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由一个单独的线程调用,该线程通过从远程节点接收新数据触发.
processChatMessage is invoked by a separate thread triggered by receiving new data from a remote node.
我认为尝试更新GUI控件时会产生该错误.
and i think the error is being produced as it trying to update GUI controls.
您认为这是原因吗?我问,因为我是Java和C#的新手,但这就是我想的.
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.
解决方案:
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){
}
}
}
}
推荐答案
最接近的等效项可能是Runnable
接口-基本上是一种单方法接口,其方法不带参数且不返回任何值.您可以使用匿名内部类来实现某物效果,例如匿名方法:
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
}
});
是的,它有点冗长...但是希望 Java 7闭包最终将可以解决:)
Yes, it's a bit verbose... but hopefully Java 7 closures will come to the rescue, eventually :)
现在,这是SwingUtilities.invokeLater(Runnable)
和SwingUtilities.invokeAndWait(Runnable)
看作是Control.BeginInvoke
和Control.Invoke
的粗略等价物.
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.
这篇关于Java C#操作委托的invokeAndWait的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!