【问题标题】:Java: Access button in another class from threadJava:从线程访问另一个类中的按钮
【发布时间】:2016-04-09 04:56:55
【问题描述】:

我有 class1 和 class2。 Class1 是一个 UI,class2 对 UI 进行更改。 Class2 如下所示。

1)有没有办法让整个class2使用class1的对象(JButton btnStartFullBuild, JButton btnShutdownServer等)

2) 如何允许线程更改 Class1 中按钮的背景颜色 (使用:btnShutdownServer.setBackground(Color.blue);

package examples;
import java.awt.Color;

import javax.swing.JButton;

public class Class2 {

    public static void shutdownServer(JButton btnStartFullBuild, JButton btnShutdownServer) {
// This works
        btnShutdownServer.setBackground(Color.blue);
// This works when passing text, but I cant modify other classes buttons
        new ThreadTest("Can I modify a button?").start();
    }


}
class ThreadTest extends Thread {
    public ThreadTest(String str) {
        super(str);
    }

    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println("Loop " + i + ": " + getName());
            try {
                sleep((int) (Math.random() * 2000));

            } catch (InterruptedException e) {
            }
        }
    }
}

【问题讨论】:

  • 你应该知道 Swing 绝对不是线程安全的。虽然您正在做的事情可能会或可能不会奏效,但这样做并不是一个好主意。
  • 我意识到我复制了一部分没有运行的代码。在我编辑了实际运行的代码部分后它就起作用了(我已经做了很多更改)

标签: java multithreading swing


【解决方案1】:

是的,但你可能不想这样做,因为Class2 可以做各种你不希望它做的讨厌的事情,比如删除按钮和其他组件

更好的解决方案是使用Observer Pattern 允许Class2 生成相关方可以响应的通知。

此外,Swing 不是线程安全的,因此在尝试从 EDT 上下文之外修改 UI 状态时要小心。

查看Concurrency in Swing 了解更多详情和其他可能的选项,例如SwingWorker(支持PropertyChange

【讨论】:

    【解决方案2】:

    我同意之前的回答,即这不是最优雅的解决方案,但是......看起来可以使用SwingUtilities.invokeLater 来做到这一点:

    // from inside your current run method
    public void run() {
        for (int i = 0; i < 5; i++) {
            ...
        // access button here
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                btnShutdownServer.setBackground(Color.blue);
            }
        });
    

    我不是 Swing 专家,在这里找到了这个解决方案:http://www.javamex.com/tutorials/threads/invokelater.shtml

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-19
      • 1970-01-01
      • 2014-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多