如何在运行代码以确定在JTextArea中显示的内容时,如何在JTextArea中完成显示进度?

时间:2016-02-24 08:23:14

标签: java jtextarea invoke progress swingutilities

我不知道这是否可行。我正在制作彩票应用程序,我正在尝试使用尽可能少的GUI组件。所以我有一个JTextArea应该显示以下消息(例如):

“计算...... 55.4%”

当我将它打印到控制台时,它显示正常,但它不会将其打印到JTextArea。我试图使用SwingUtilities.invokeLater,但这也不起作用。

    for (int x = 0; x < daysBetween; x++)
    {
      completion = "Calculating..." + df.format((100 * (x + 1)) / daysBetween) + "%";
      if (!textArea.getText().equals(completion))
      {
        textArea.setText(completion);
      }
      /*
      Here I have a lot of irrelevant code that compares your tickets to the winning tickets and counts your winnings and other statistics...
      */
    }

    ticketReport += "Computation time: " + getElapsedTime(start, System.nanoTime());
    ticketReport += "\nEnd date: " + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.DAY_OF_MONTH) + "/" + cal.get(Calendar.YEAR); 
    ticketReport += "\nTotal # of tickets purchased: " + numOfTicketsPurchased;
    /*
    etc. with filling out the ticket report
    */
    textArea.setText(ticketReport);

你可以猜到,我希望更新JTextArea,因为我在上面的for循环中设置了textArea的文本。它直到方法结束时才更新JTextArea,这是我设置文本区域以显示故障单报告的最底层。

Lottery Fever application http://i63.tinypic.com/2s85j5t.png

MY END GOAL:我想最终将其转变为Android手机应用程序,这就是为什么我不想使用任何弹出窗口或任何东西。

2 个答案:

答案 0 :(得分:0)

/ * 编辑:这暂时解决了问题,但我遇到了另一个问题。现在,当我尝试通过调用带有参数true的cancel方法来取消SwingWorker时,它不会取消。请参阅我解决此问题的方法的其他答案。 * /

我明白了。我把上面的方法放在SwingWorker中,如下所示:

      SwingWorker<Void, Void> sw = new SwingWorker<Void, Void>()
      {
        @Override
        protected Void doInBackground() throws Exception
        {
          //method here
        }
      }

在该方法中,我使用参数&#34;(100 *(x + 1))/ daysBetween&#34;调用了setProgress方法。显示正确的完成百分比。然后,我补充说:

      sw.execute();
      sw.addPropertyChangeListener(new PropertyChangeListener()
      {
        @Override
        public void propertyChange(PropertyChangeEvent arg0)
        {
          textArea.setText("Calculating..." + sw.getProgress() + "%");
          if (sw.getProgress() == 100)
            textArea.setText(ticketReport);
        }
      });

它显示百分比为整数而不是#。##我最初想要的,但如果我愿意,我可以很容易地改变。

答案 1 :(得分:0)

我最初的SwingWorker方法使它在JTextArea中显示完成百分比状态。我添加了一个取消操作的选项,当我尝试取消时,“线程”(SwingWorker)不会取消。当我取消并重新启动时,它会不断堆叠。另一个连续启动而另一个启动将导致计算变得越来越慢,然后提供不正确的信息。

我第二次这样做的方式解决了原来的问题和这个新问题。我创建了一个新的私有类,它扩展了Thread,覆盖了它的run()方法,并在该方法的线程中插入了要执行的代码。我注意到任何停止线程的方法都因为潜在的问题而被弃用,所以我创建了一个布尔值,当用户请求停止线程时设置它,并且在线程内它定期读取布尔值,然后当它等于时退出为真。

我启动线程的方法是重新初始化对象BackgroundCalc并调用其start()方法。

  private class BackgroundCalc extends Thread
  {
    public void run()
    {
      /*
      initializing stuff here
      */
      for (int x = 0; x < daysBetween; x++)
      {
        progress = (100 * (x + 1)) / daysBetween;
        if (destroyCalcThread) return;
        /*
        background calculations here
        */
      }
      /*
      finish up thread here
      */
    }
  }

我对线程缺乏经验,所以希望我在这里的斗争以及我解释它的方式将帮助那些对这个概念缺乏经验的人。

相关问题