java - Java 中的计数 - 文本字段仅显示最后一个值

标签 java swing counter event-dispatch-thread counting

我在 Java 中模拟处理器计数器时遇到问题。我想从 0 到 6 进行计数,并在文本字段中显示当前的计数值(0、1、2、3、4、5、6)。当我单击“计数”按钮时,我的程序卡住了一会儿,在文本字段中计数后我只能看到数字 6。我想在计数过程中看到其他数字。这是我的代码的一部分:

for (int b=0; b<30; b++)
        {
           counter2.Count();
           try {
                    Thread.sleep(300);
                } catch(InterruptedException e){}
           text6.setText("TEST" + counter2.MainReg); }

我可以用它做什么? 谢谢你帮助我。

最佳答案

您需要将计算放在一个工作线程上。来自甲骨文:

When a Swing program needs to execute a long-running task, it usually uses one of the worker threads, also known as the background threads. Each task running on a worker thread is represented by an instance of javax.swing.SwingWorker. SwingWorker itself is an abstract class; you must define a subclass in order to create a SwingWorker object; anonymous inner classes are often useful for creating very simple SwingWorker objects.

您可以访问以下链接并了解如何操作:

http://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html

下面是 Oracle 提供的有关如何实现 SwingWorker 类中的方法的示例。 http://docs.oracle.com/javase/tutorial/uiswing/concurrency/simple.html

由于您希望能够在过程发生时看到结果,因此您可以遵循 Oracle 中的以下示例:http://docs.oracle.com/javase/tutorial/uiswing/concurrency/interim.html

编辑:正如 mKorbel 在下面的评论中所建议的,您还可以使用 Swing 计时器,如下所述:http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html

关于java - Java 中的计数 - 文本字段仅显示最后一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16022533/

相关文章:

java - hashCode() 可以有动态变化的内容吗?

java - 获得对 JPanel 的关注

java - 如何在Java中使用GridLayout?

php - 使用 php 和 js 的简单点击计数器

c - 为什么我的 for 循环没有在 C 中给出预期的输出?

java - 想要在标签中显示日期

java - 使 else 语句执行与 if 语句相反的操作

java - 数组和扩展的困境

java - 如何在 Selenium Web 驱动程序中单击下一个 span 元素

java - 将 JTextField 的输入限制为双数?