gpt4 book ai didi

java - 2 个线程和 2 个 JTextArea

转载 作者:太空宇宙 更新时间:2023-11-04 07:07:47 25 4
gpt4 key购买 nike

我需要编写显示 2 个不同 JTextArea 中线程给出的时间的程序。时间每隔随机时间段更新一次。线程也可以通过按钮停止并通过再次 clang 恢复。我在其他类(class)中拥有所有 GUI。

我的问题:如何在其他类中添加对 JTextArea 的引用?如何使用按钮停止线程并恢复?

这里是 Thread 类的代码:

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.swing.JTextArea;

public class MyThread implements Runnable {
StopResume main = new StopResume();
String name;
Thread t;
JTextArea a;

String date;
DateFormat to = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date today = Calendar.getInstance().getTime();

public MyThread(String threatName) {
name = threatName;
t = new Thread(this, name);
t.start();
}

public static void main(String[] args) {
//area1.append(date);
//area2.append(date);
//date = to.format(today);
}


@Override
public void run() {
try {
for(int i = 0; i < 20; i++){
t.sleep(1000);

}
}catch (InterruptedException e) {
e.printStackTrace();
}
}
}

最佳答案

您的问题和我尝试回答:

My problem: How to add reference to JTextArea in other class ?

我建议您不要像一般情况一样,一个对象不应该直接操作另一个对象的字段。相反,让您的线程保存对 GUI 的引用,并让它调用接受字符串的 GUI 的公共(public)方法,其中 GUI 将附加到 JTextArea。另外,请确保仅在 Swing 事件线程或 EDT 上调用此方法。这可以通过调用 SwingUtilities.invokeLater(yourRunnable) 将 Runnable 排队到 EDT 来完成。或者更好——使用 SwingWorker。有关更多信息,请阅读Concurrency in Swing Tutorial .

How to stop Thread and resume with buttons ?

为控制类(ActionListener 类)提供对线程的引用,并在 ActionListener 中调用停止或恢复线程 while 循环的公共(public)方法(可能通过更改 boolean 变量)。

<小时/>

进一步说明:

  • 我发现您的 Thread.sleep(...) 延迟时间没有随机性。您是否需要为 MyThread 类提供一个 Random 对象并使用它来更改 Thread.sleep(...) 时间?
  • 我发现您使用的是 for 循环而不是 while 循环 - 您确定应该这样做吗?
  • 我没有看到您的线程类有任何机制来暂停其循环。同样,可以检查和更改其 boolean 条件的 while 循环可能会更好 - 由您决定。
  • 您的线程类创建自己的 StopResume 对象副本。如果这是您的主要 GUI,那么您就会遇到麻烦。您应该传入对显示的 GUI 的有效引用,可能是通过该线程类的构造函数。

关于java - 2 个线程和 2 个 JTextArea,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21078466/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com