10

为了SwingTimer准确起见,我喜欢@Tony Docherty On CR 提出的逻辑和示例。这是链接

为了一次又一次地突出给定的单词,总是会有几微秒的延迟。如果我要突出显示的话:“你好,怎么样”并且每个词的值分别是(延迟):200,300,400 ms,那么计时器所花费的实际时间总是更多。说不是 200 毫秒,而是 216 毫秒。像这样,如果我有很多话..最后,额外的延迟是显而易见的。

我必须突出显示每个字母说:'h''e''l''l''0' 每个应该得到 200/length(ie 5) = 40 ms 大约。在每个字母之后设置延迟。

我的逻辑是,以当前时间为例startTime,就在开始该过程之前。另外,计算totalDelay哪个是totalDelay+=delay/.length()。

现在检查条件: ( startTime+totalDelay-System.currentTime) 如果这是-ve,则表示时间消耗更多,因此跳过该字母。检查直到有一个积极的延迟。这意味着我正在添加时间到现在,并过度检查它与进程开始时所用时间的差异。

这可能会导致跳过以突出显示字母。

但有些不对劲。什么,我很难分辨。循环的东西可能有问题。我已经看到它只是两次进入循环(检查时间是否为 -ve )。但事实并非如此。而且我也不确定设置我的下一个延迟。有任何想法吗?

这是一个SSCCE:

    import java.awt.Color;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.lang.reflect.InvocationTargetException;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTextPane;
    import javax.swing.SwingUtilities;
    import javax.swing.Timer;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.DefaultStyledDocument;
    import javax.swing.text.StyleConstants;
    import javax.swing.text.StyledDocument;

    public class Reminder {
        private static final String TEXT = "arey chod chaad ke apnee saleem ki gali anarkali disco chalo";
        private static final String[] WORDS = TEXT.split(" ");
        private JFrame frame;
        private Timer timer;
        private StyledDocument doc;
        private JTextPane textpane;
        private int[] times = new int[100];
      private long totalDelay=0,startTime=0;

        private int stringIndex = 0;
        private int index = 0;

        public void startColoring() {
              times[0]=100;times[9]=200;times[10]=200;times[11]=200;times[12]=200;
              times[1]=400;times[2]=300;times[3]=900;times[4]=1000;times[5]=600;times[6]=200;times[7]=700;times[8]=700;

      ActionListener actionListener = new ActionListener() {
       @Override
       public void actionPerformed(ActionEvent actionEvent) 
       {

       doc.setCharacterAttributes(stringIndex, 1, textpane.getStyle("Red"), true);
        stringIndex++;

 try {

 if (stringIndex >= doc.getLength() || doc.getText(stringIndex, 1).equals(" ")|| doc.getText(stringIndex, 1).equals("\n"))
 {
                            index++;
  }
    if (index < WORDS.length) {

       double delay = times[index];
     totalDelay+=delay/WORDS[index].length();

  /*Check if there is no -ve delay, and you are running according to the time*/
  /*The problem is here I think. It's just entered this twice*/
   while(totalDelay+startTime-System.currentTimeMillis()<0)
      { 
      totalDelay+=delay/WORDS[index].length();
      stringIndex++;
     /*this may result into the end of current word, jump to next word.*/
    if (stringIndex >= doc.getLength() || doc.getText(stringIndex, 1).equals(" ") || doc.getText(stringIndex, 1).equals("\n"))
       {
   index += 1;
   totalDelay+=delay/WORDS[index].length();
       }
      }

     timer.setDelay((int)(totalDelay+startTime-System.currentTimeMillis()));

                        } 
else {
         timer.stop();
    System.err.println("Timer stopped");
       }
                    } catch (BadLocationException e) {
                        e.printStackTrace();
                    }
                }
            };

            startTime=System.currentTimeMillis();
            timer = new Timer(times[index], actionListener);
            timer.setInitialDelay(0);
            timer.start();
        }

        public void initUI() {
            frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JPanel panel = new JPanel();
            doc = new DefaultStyledDocument();
            textpane = new JTextPane(doc);
            textpane.setText(TEXT);
            javax.swing.text.Style style = textpane.addStyle("Red", null);
            StyleConstants.setForeground(style, Color.RED);
            panel.add(textpane);
            frame.add(panel);
            frame.pack();
            frame.setVisible(true);
        }

        public static void main(String args[]) throws InterruptedException, InvocationTargetException {
            SwingUtilities.invokeAndWait(new Runnable() {
                @Override
                public void run() {
                    Reminder reminder = new Reminder();
                    reminder.initUI();
                    reminder.startColoring();
                }
            });
        }
    }

更新:

为了更好地理解:

@Tony Docherty 给出的 EG:

让我们以单词“Test”为例,说它需要突出显示 1 秒,因此每个字母突出显示 250 毫秒。以您最初的方式做事,确实意味着您为每个字母设置了一个 250 毫秒的计时器,但如果每个周期实际上花费了 260 毫秒,并且假设“e”周期花费了 400 毫秒(可能是由于 GC 或其他使用 CPU 周期的原因)你会比你应该多花 180 毫秒。这个错误将继续为每个单词构建,直到错误如此之大,突出显示不再在视觉上同步。

我正在尝试的方法是,而不是反复说这个字母需要突出显示 x 时间,计算每个字母相对于序列开头的时间,即 T = 250, e = 500, s = 750, t = 1000。

因此,要获得实际的时间延迟,您需要添加开始时间并减去当前时间。使用我上面给出的时间来运行示例:

StartTime   Letter   Offset    CurrentTime    Delay  ActualTimeTaken   
100000         T       250       100010        240      250  
100000         e       500       100260        240      400  
100000         s       750       100660         90      100  
100000         t      1000       100760        240      250  

因此,您现在应该能够看到,每个字母的时间都经过调整,以考虑到前一个字母的时间超限。当然,时间超限可能非常大,以至于您必须跳过突出显示下一个字母(或者可能超过 1 个),但至少我会保持大致同步。

编辑的 SSCCE

更新2

在第一阶段,我为每个单词计时。也就是说,当用户按下 ESC 键时,会存储特定单词的时间(他这样做是因为在后台播放歌曲。)当按下 ESC 键时,当前单词会突出显示,并且当前单词所花费的时间单词存储在一个数组中。我继续存储时间。当用户结束时,现在我想根据设定的时间突出显示单词。所以在这里,用户的时机很重要。如果时间很快,单词的突出显示也是如此,或者如果很慢,反之亦然。

新更新:进度

下面的答案有不同的逻辑,但令我惊讶的是,它们或多或少是相同的。我发现所有逻辑(包括我的逻辑)的一个非常非常奇怪的问题是,它们似乎在几行代码中都能完美运行,但在那之后它们的速度也不是很慢,而是有很大的不同。

此外,如果您认为我应该以不同的方式思考,我们非常感谢您的建议。

4

4 回答 4

7

我认为要做这样的事情,你需要一个摆动定时器,它以恒定的速率滴答作响,比如 15 毫秒,只要它足够快以允许你需要的时间粒度,然后当经过的时间是你需要的。

  • 换句话说,根本不要改变Timer的延迟,而只是根据你的需要改变所需的经过时间。
  • 你不应该while (true)在 EDT 上有一个循环。让“while 循环”成为 Swing Timer 本身。
  • 为了使您的逻辑更加万无一失,您需要检查经过的时间是否 >= 需要的时间。
  • 同样,不要设置定时器的延迟。换句话说,不要将它用作计时器,而是用作轮询器。让它每隔 xx 毫秒不停地轮询经过的时间,然后在经过的时间 >= 满足您的需要时做出反应。

我建议的代码看起来像这样:

     public void actionPerformed(ActionEvent actionEvent) {

        if (index > WORDS.length || stringIndex >= doc.getLength()) {
           ((Timer)actionEvent.getSource()).stop();
        }

        currentElapsedTime = calcCurrentElapsedTime();
        if (currentElapsedTime >= elapsedTimeForNextChar) {
           setNextCharAttrib(stringIndex);
           stringIndex++;

           if (atNextWord(stringIndex)) {
              stringIndex++; // skip whitespace 
              deltaTimeForEachChar = calcNextCharDeltaForNextWord();
           } else {
              elapsedTimeForNextChar += deltaTimeForEachChar;
           }
        }

        // else -- we haven't reached the next time to change char attribute yet.
        // keep polling.
     }

例如,我的 SSCCE:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.LinkedList;
import java.util.List;

import javax.swing.*;
import javax.swing.text.*;

public class Reminder3 {
   private static final String TEXT = "arey chod chaad ke apnee saleem ki gali anarkali disco chalo";
   private static final String[] WORDS = TEXT.split(" ");
   private static final int[] TIMES = { 100, 400, 300, 900, 1000, 600, 200,
         700, 700, 200, 200, 200, 200 };
   private static final int POLLING_TIME = 12;

   private StyledDocument doc;
   private JTextPane textpane;
   private JPanel mainPanel = new JPanel();
   private List<ReminderWord> reminderWordList = new LinkedList<ReminderWord>();
   private Timer timer;

   // private int stringIndex = 0;

   public Reminder3() {
      doc = new DefaultStyledDocument();
      textpane = new JTextPane(doc);
      textpane.setText(TEXT);
      javax.swing.text.Style style = textpane.addStyle("Red", null);
      StyleConstants.setForeground(style, Color.RED);

      JPanel textPanePanel = new JPanel();
      textPanePanel.add(new JScrollPane(textpane));

      JButton startBtn = new JButton(new AbstractAction("Start") {

         @Override
         public void actionPerformed(ActionEvent arg0) {
            goThroughWords();
         }
      });
      JPanel btnPanel = new JPanel();
      btnPanel.add(startBtn);

      mainPanel.setLayout(new BorderLayout());
      mainPanel.add(textPanePanel, BorderLayout.CENTER);
      mainPanel.add(btnPanel, BorderLayout.SOUTH);
   }

   public void goThroughWords() {
      if (timer != null && timer.isRunning()) {
         return;
      }
      doc = new DefaultStyledDocument();
      textpane.setDocument(doc);
      textpane.setText(TEXT);

      javax.swing.text.Style style = textpane.addStyle("Red", null);
      StyleConstants.setForeground(style, Color.RED);

      int wordStartTime = 0;
      for (int i = 0; i < WORDS.length; i++) {

         if (i > 0) {
            wordStartTime += TIMES[i - 1];
         }
         int startIndexPosition = 0; // set this later
         ReminderWord reminderWord = new ReminderWord(WORDS[i], TIMES[i],
               wordStartTime, startIndexPosition);
         reminderWordList.add(reminderWord);
      }

      int findWordIndex = 0;
      for (ReminderWord word : reminderWordList) {

         findWordIndex = TEXT.indexOf(word.getWord(), findWordIndex);
         word.setStartIndexPosition(findWordIndex);
         findWordIndex += word.getWord().length();
      }

      timer = new Timer(POLLING_TIME, new TimerListener());
      timer.start();
   }

   public JComponent getMainPanel() {
      return mainPanel;
   }


   private void setNextCharAttrib(int textIndex) {
      doc.setCharacterAttributes(textIndex, 1,
            textpane.getStyle("Red"), true);      
   }

   private class TimerListener implements ActionListener {
      private ReminderWord currentWord = null;
      private long startTime = System.currentTimeMillis();

      @Override
      public void actionPerformed(ActionEvent e) {
         if (reminderWordList == null) { 
            ((Timer) e.getSource()).stop();
            return;
         }

         if (reminderWordList.isEmpty() && currentWord.atEnd()) {
            ((Timer) e.getSource()).stop();
            return;
         }

         // if just starting, or if done with current word
         if (currentWord == null || currentWord.atEnd()) {
            currentWord = reminderWordList.remove(0); // get next word
         }

         long totalElapsedTime = System.currentTimeMillis() - startTime;
         if (totalElapsedTime > (currentWord.getStartElapsedTime() + currentWord
               .getIndex() * currentWord.getTimePerChar())) {
            setNextCharAttrib(currentWord.getStartIndexPosition() + currentWord.getIndex());

            currentWord.increment();
         }

      }
   }

   private static void createAndShowGui() {
      Reminder3 reminder = new Reminder3();

      JFrame frame = new JFrame("Reminder");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(reminder.getMainPanel());
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }


   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }

}

class ReminderWord {
   private String word;
   private int totalTime;
   private int timePerChar;
   private int startTime;
   private int startIndexPosition;
   private int index = 0;

   public ReminderWord(String word, int totalTime, int startTime,
         int startIndexPosition) {
      this.word = word;
      this.totalTime = totalTime;
      this.startTime = startTime;
      timePerChar = totalTime / word.length();
      this.startIndexPosition = startIndexPosition;
   }

   public String getWord() {
      return word;
   }

   public int getTotalTime() {
      return totalTime;
   }

   public int getStartElapsedTime() {
      return startTime;
   }

   public int getTimePerChar() {
      return timePerChar;
   }

   public int getStartIndexPosition() {
      return startIndexPosition;
   }

   public int increment() {
      index++;
      return index;
   }

   public int getIndex() {
      return index;
   }

   public boolean atEnd() {
      return index > word.length();
   }

   public void setStartIndexPosition(int startIndexPosition) {
      this.startIndexPosition = startIndexPosition;
   }

   @Override
   public String toString() {
      return "ReminderWord [word=" + word + ", totalTime=" + totalTime
            + ", timePerChar=" + timePerChar + ", startTime=" + startTime
            + ", startIndexPosition=" + startIndexPosition + ", index=" + index
            + "]";
   }

}
于 2013-02-23T13:39:42.070 回答
5

好的,所以我一直在查看一些代码(我在您关于卡拉 OK 计时器的最后一个问题中发布的代码)

使用该代码,我建立了一些测量系统,使用System.nanoTime()viaSystem.out.println()这将帮助我们了解正在发生的事情:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;

public class KaraokeTest {

    private int[] timingsArray = {1000, 1000, 9000, 1000, 1000, 1000, 1000, 1000, 1000, 1000};//word/letters timings
    private String[] individualWordsToHighlight = {" \nHello\n", " world\n", " Hello", " world", " Hello", " world", " Hello", " world", " Hello", " world"};//each individual word/letters to highlight
    private int count = 0;
    private final JTextPane jtp = new JTextPane();
    private final JButton startButton = new JButton("Start");
    private final JFrame frame = new JFrame();
    //create Arrays of individual letters and their timings
    final ArrayList<String> chars = new ArrayList<>();
    final ArrayList<Long> charsTiming = new ArrayList<>();

    public KaraokeTest() {
        initComponents();
    }

    private void initComponents() {
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);

        for (String s : individualWordsToHighlight) {
            String tmp = jtp.getText();
            jtp.setText(tmp + s);
        }
        jtp.setEditable(false);

        startButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                startButton.setEnabled(false);
                count = 0;
                charsTiming.clear();
                chars.clear();

                for (String s : individualWordsToHighlight) {
                    for (int i = 0; i < s.length(); i++) {
                        chars.add(String.valueOf(s.charAt(i)));
                        //System.out.println(String.valueOf(s.charAt(i)));
                    }
                }

                //calculate each letters timings
                for (int x = 0; x < timingsArray.length; x++) {
                    for (int i = 0; i < individualWordsToHighlight[x].length(); i++) {
                        individualWordsToHighlight[x] = individualWordsToHighlight[x].replace("\n", " ").replace("\r", " ");//replace line breaks
                        charsTiming.add((long) (timingsArray[x] / individualWordsToHighlight[x].trim().length()));//dont count spaces
                        //System.out.println(timingsArray[x] / individualWordsToHighlight[x].length());
                    }
                }

                Timer t = new Timer(1, new AbstractAction() {
                    long startTime = 0;
                    long acum = 0;
                    long timeItTookTotal = 0;
                    long dif = 0, timeItTook = 0, timeToTake = 0;
                    int delay = 0;

                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        if (count < charsTiming.size()) {

                            if (count == 0) {
                                startTime = System.nanoTime();
                                System.out.println("Started: " + startTime);
                            }

                            timeToTake = charsTiming.get(count);
                            acum += timeToTake;

                            //highlight the next word
                            highlightNextWord();

                            //System.out.println("Acum " + acum);
                            timeItTook = (acum - ((System.nanoTime() - startTime) / 1000000));
                            timeItTookTotal += timeItTook;
                            //System.out.println("Elapsed since start: " + (System.nanoTime() - startTime));
                            System.out.println("Time the char should take: " + timeToTake);
                            System.out.println("Time it took: " + timeItTook);
                            dif = (timeToTake - timeItTook);
                            System.out.println("Difference: " + dif);
                            //System.out.println("Difference2 " + (timeToTake - dif));

                            //calculate start of next letter to highlight less the difference it took between time it took and time it should actually take
                            delay = (int) (timeToTake - dif);

                            if (delay < 1) {
                                delay = 1;
                            }

                            //restart timer with new timings
                            ((Timer) ae.getSource()).setInitialDelay((int) timeToTake);//timer is usually faster thus the entire highlighting will be done too fast
                            //((Timer) ae.getSource()).setInitialDelay(delay);
                            ((Timer) ae.getSource()).restart();

                        } else {//we are at the end of the array
                            long timeStopped = System.nanoTime();
                            System.out.println("Stopped: " + timeStopped);
                            System.out.println("Time it should take in total: " + acum);
                            System.out.println("Time it took using accumulator of time taken for each letter: " + timeItTookTotal
                                    + "\nDifference: " + (acum - timeItTookTotal));
                            long timeItTookUsingNanoTime = ((timeStopped - startTime) / 1000000);
                            System.out.println("Time it took using difference (endTime-startTime): " + timeItTookUsingNanoTime
                                    + "\nDifference: " + (acum - timeItTookUsingNanoTime));
                            reset();
                            ((Timer) ae.getSource()).stop();//stop the timer
                        }
                        count++;//increment counter
                    }
                });
                t.setRepeats(false);
                t.start();
            }
        });

        frame.add(jtp, BorderLayout.CENTER);
        frame.add(startButton, BorderLayout.SOUTH);

        frame.pack();
        frame.setVisible(true);
    }

    private void reset() {
        startButton.setEnabled(true);
        jtp.setText("");
        for (String s : individualWordsToHighlight) {
            String tmp = jtp.getText();
            jtp.setText(tmp + s);
        }
        JOptionPane.showMessageDialog(frame, "Done");
    }

    private void highlightNextWord() {
        //we still have words to highlight
        int sp = 0;
        for (int i = 0; i < count + 1; i++) {//get count for number of letters in words (we add 1 because counter is only incrementd after this method is called)
            sp += 1;
        }

        while (chars.get(sp - 1).equals(" ")) {
            sp += 1;
            count++;
        }

        //highlight words
        Style style = jtp.addStyle("RED", null);
        StyleConstants.setForeground(style, Color.RED);
        ((StyledDocument) jtp.getDocument()).setCharacterAttributes(0, sp, style, true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new KaraokeTest();
            }
        });
    }
}

我的电脑上的输出是:

开始:10289712615974

char 应该花费的时间:166

花费时间:165

差异1

...

char 应该花费的时间:166

花费时间:155

差异 11

...

char 应该花费的时间:166

花费时间:5

差异161

已停止:10299835063084

总共应该花费的时间:9960

使用每个字母所用时间的累加器所花费的时间:5542

差异:4418

使用差异所花费的时间(endTime-startTime):10122

差异:-162

因此,我的结论是 Swing Timer 实际上运行得比我们预期的要快,因为Timers中的代码actionPerformed不一定需要与预期突出显示时间一样长的字母,这当然会导致雪崩效应,即计时器运行得越快/越慢/差异将变得更少,并且下次执行的计时器restart(..)将在不同的时间进行,即更快或更慢。

在代码中这样做:

//calculate start of next letter to highlight less the difference it took between time it took and time it should actually take
delay = (int) (timeToTake - dif);


//restart timer with new timings
//((Timer) ae.getSource()).setInitialDelay((int)timeToTake);//timer is usually faster thus the entire highlighting will be done too fast
((Timer) ae.getSource()).setInitialDelay(delay);
((Timer) ae.getSource()).restart();

产生更准确的结果(我的最大延迟比每个字母快 4 毫秒):

开始:10813491256556

char 应该花费的时间:166

花费时间:164

差异 2

...

char 应该花费的时间:166

花费时间:164

差异 2

...

char 应该花费的时间:166

花费时间:162

差异 4

已停止:10823452105363

总共应该花费的时间:9960

使用每个字母所用时间的累加器所用的时间:9806

差异:154

使用差异所花费的时间(endTime-startTime):9960

差异:0

于 2013-02-27T17:30:27.810 回答
4

你考虑过 java.util.Timer 和 scheduleAtFixedRate 吗?你需要做一些额外的工作才能在 EDT 上做一些事情,但它应该可以解决累积延迟的问题。

于 2013-02-23T15:17:06.590 回答
4

ScheduledExecutorService往往比 Swing 的 Timer 更准确,并且它提供了运行多个线程的好处。特别是,如果一个任务延迟,它不会影响下一个任务的开始时间(在一定程度上)。

显然,如果任务在 EDT 上花费的时间太长,这将成为您的限制因素。

请参阅下面基于您的提议的 SSCCE - 我还稍微重构了该startColoring方法并将其拆分为几种方法。我还添加了一些“日志记录”以获取有关操作时间的反馈。完成后不要忘记shutdown执行程序,否则可能会阻止程序退出。

每个单词开始着色时都会有轻微的延迟(在我的机器上介于 5 到 20 毫秒之间),但延迟不是累积的。您实际上可以测量调度开销并进行相应调整。

public class Reminder {

    private static final String TEXT = "arey chod chaad ke apnee saleem ki gali anarkali disco chalo\n" +
            "arey chod chaad ke apnee saleem ki gali anarkali disco chalo\n" +
            "arey chod chaad ke apnee saleem ki gali anarkali disco chalo\n" +
            "arey chod chaad ke apnee saleem ki gali anarkali disco chalo\n" +
            "arey chod chaad ke apnee saleem ki gali anarkali disco chalo\n" +
            "arey chod chaad ke apnee saleem ki gali anarkali disco chalo";
    private static final String[] WORDS = TEXT.split("\\s+");
    private JFrame frame;
    private StyledDocument doc;
    private JTextPane textpane;
    private static final int[] TIMES = {100, 400, 300, 900, 1000, 600, 200, 700, 700, 200, 200, 
                                        100, 400, 300, 900, 1000, 600, 200, 700, 700, 200, 200,
                                        100, 400, 300, 900, 1000, 600, 200, 700, 700, 200, 200,
                                        100, 400, 300, 900, 1000, 600, 200, 700, 700, 200, 200,
                                        100, 400, 300, 900, 1000, 600, 200, 700, 700, 200, 200,
                                        100, 400, 300, 900, 1000, 600, 200, 700, 700, 200, 200, 200};
    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);
    private int currentLetterIndex;
    private long start; //for logging

    public void startColoring() {
        start = System.currentTimeMillis(); //for logging
        int startTime = TIMES[0];
        for (int i = 0; i < WORDS.length; i++) {
            scheduler.schedule(colorWord(i, TIMES[i + 1]), startTime, TimeUnit.MILLISECONDS);
            startTime += TIMES[i+1];
        }
        scheduler.schedule(new Runnable() {

            @Override
            public void run() {
                scheduler.shutdownNow();
            }
        }, startTime, TimeUnit.MILLISECONDS);
    }

    //Color the given word, one letter at a time, for the given duration
    private Runnable colorWord(final int wordIndex, final int duration) {
        final int durationPerLetter = duration / WORDS[wordIndex].length();
        final int wordStartIndex = currentLetterIndex;
        currentLetterIndex += WORDS[wordIndex].length() + 1;
        return new Runnable() {
            @Override
            public void run() {
                System.out.println((System.currentTimeMillis() - start) + " ms - Word: " + WORDS[wordIndex] + "  - duration = " + duration + "ms");
                for (int i = 0; i < WORDS[wordIndex].length(); i++) {
                    scheduler.schedule(colorLetter(wordStartIndex + i), i * durationPerLetter, TimeUnit.MILLISECONDS);
                }
            }
        };
    }

    //Color the letter on the EDT
    private Runnable colorLetter(final int letterIndex) {
        return new Runnable() {
            @Override
            public void run() {
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        System.out.println("\t" + (System.currentTimeMillis() - start) + " ms - letter: " + TEXT.charAt(letterIndex));
                        doc.setCharacterAttributes(letterIndex, 1, textpane.getStyle("Red"), true);
                    }
                });
            }
        };
    }

    public void initUI() {
        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new JPanel();
        doc = new DefaultStyledDocument();
        textpane = new JTextPane(doc);
        textpane.setText(TEXT);
        javax.swing.text.Style style = textpane.addStyle("Red", null);
        StyleConstants.setForeground(style, Color.RED);
        panel.add(textpane);
        frame.add(panel);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String args[]) throws InterruptedException, InvocationTargetException {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                Reminder reminder = new Reminder();
                reminder.initUI();
                reminder.startColoring();
            }
        });
    }
}
于 2013-02-25T17:39:45.970 回答