Java 类之间的消息传递如何最好地完成?
我有多个类和线程需要写入 Java Swing JScrollPane。在Android/Eclipse环境中我使用了android.os.Message。 NetBeans/Windows 环境中是否有类似的东西?这是我想从以下位置发送消息的位置:
public class PrintStatusTask extends Thread {
PrintStatusTask(String name) {
this.name = name;
}
private void sendMessage(String s) {
// TODO: send message to jTextArea
}
public void run() {
...
sendMessage("Any message");
...
这是从 JFrame 所在的 JScrollPane 写入 JScrollPane 的示例:
public class Controller extends javax.swing.JFrame implements Observer {
...
jTextArea.append(s);
...
I have multiple classes and threads that need to write to a Java Swing JScrollPane. In the Android/Eclipse environment I used android.os.Message. Is there something similar in the NetBeans/Windows environment? Here is where I would like to send the message from:
public class PrintStatusTask extends Thread {
PrintStatusTask(String name) {
this.name = name;
}
private void sendMessage(String s) {
// TODO: send message to jTextArea
}
public void run() {
...
sendMessage("Any message");
...
Here is an example of writing to the JScrollPane from the JFrame it lives in:
public class Controller extends javax.swing.JFrame implements Observer {
...
jTextArea.append(s);
...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您要写入窗格本身(即更改视图上的数据),那么最好的方法是使用 swing 工作线程,并稍后执行它:(
语法可能略有偏差 - 我是从内存中执行的)
If you are writing to the pane itself (i.e. changing the data on the view) then the best way is to use a swing worker thread, and execute it later:
(Syntax might be slightly off - I am doing it from memory)
我会赞同aperkins建议使用
SwingWorker
作为更强大的通用解决方案。在
append()
:“此方法是线程安全的,尽管大多数 Swing 方法都不是。”这是使用另一个线程的方法的简单示例。I'll second aperkins' suggestion to use
SwingWorker
as a more robust, general purpose solution.In the particular case of
append()
: "This method is thread safe, although most Swing methods are not." Here is a simple example of using the method from another thread.