1


Hello!

I am trying to display a text on the Screen (with Java), but I want it to be delayed, like, every 0.1 seconds, a letter of the text would appear on the screen. It's like Pokemons dialogs. Here's what I am talking about: https://www.youtube.com/watch?v=yUS1IcC5CBY

I don't want the fade and the acceleration of the text, I just want the text to appear letter-by-letter. Also, I would like the text to be a String. Please, can you help me?

Thanks a lot in advance!

user3658616
  • 33
  • 1
  • 1
  • 6

4 Answers4

1

You can use two methods:

One is Thread.sleep(), which is shown above:

private static String message = "Your Message";
private static JLable label = new JLabel();
private static String labelMessage = "";
for(int i = 0; i < message.length(); i++){
    labelMessage += Character.toString(message.charAt(i));
    label.setText(labelMessage);
    try{
        Thread.sleep(howManyMillisecondsYouShouldWait);//if you want to do it every .1
        //seconds, just wait 100 milliseconds.
    }catch(InterruptedException e){
        Thread.currentThread().interrupt();
    }
}

that will forever print it to the screen every 100 milliseconds. However, the only trouble with using Thread.sleep is (and I somehow just learned this the other day, even though I've been programming for a long while) it is not always accurate. It may sleep 100 ms, it may sleep 150, etc. Secondly, a slower computer may take longer to sleep through it.

The other method which you will use more often (probably) is to check the actual time of your system and see if it's been long enough since you last printed it to the screen, like this:

private static long timeOfLastWrite;//at what time did you last update the text?
private static long deltaTimeSinceLastWrite;//how long has it been since you last updated the text?
private static long timeOfFirstWrite;//when did you start?
private static long deltaTimeSinceFirstWrite;//how long has it been since you started?
private static String message = "Your Message";
private static JLabel label = new JLabel();
private static String labelMessage = "";
//print once here:
timeOfFirstWrite = System.currentTimeMillis();
timeOfLastWrite = System.currentTimeMillis();//every time you print to the screen, make
//sure that you make note of it by setting the timeOfLastWrite variable equal to the current time.
labelMessage += Character.toString(message.chatAt(0));
while(!labelMessage.equals(message)){
    deltaTimeSinceLastWrite = System.currentTimeMillis() - timeOfLastWrite;
    if(deltaTimeSinceLastWrite >= 100){
        timeOfLastWrite = System.currentTimeMillis();
        deltaTimeSinceFirstWrite = System.currentTimeMillis() - timeOfFirstWrite;
        int currentIndexOfChain = (int) deltaTimeSinceFirstWrite / 100;
        if(currentIndexOfChain >= message.length()){
            currentIndexOfChain = message.length() - 1;
        }
        labelMessage = message.substring(0, currentIndexOfChain + 1);
        label.setText(labelMessage);
    }
}

This method isn't even slightly necessary for a program so simple as writing text to the screen 10 times a second. However, it's good to get into the practice of it. You'll learn that if you create a character and tell him to move 10 pixels, Thread.sleep(100), and move again and etc... that on a slower computer, the character will move slower. However, if you tell it to wait until a certain amount of time has passed according to your computer's time, if the user lags out and it takes 200 milliseconds before it tells the character to move again, you can account for that by simply making him move twice as far -- I think it's called framerate independence.

If I did anything wrong with the delta time management please let me now. Again, I just learned about this the other day even though I've been programming for awhile, so don't worry about it too much if you're just now learning to program.

And that's how you make an incredibly long (possibly too long) answer to an incredibly simple question. I hope you benefit from this response.

Alexander Guyer
  • 2,063
  • 1
  • 14
  • 20
  • So what I did is take how long it's been since the program first started, and then divide that by 100 to get how many hundreds of milliseconds have passed since then. Then, I take this number, and add one to it (because we started out with one character) and get the substring of the message we want the label to eventually equal starting at 0 and working all the way toward that number (time since start / 100, plus 1). I tested it in an applied way with System.out.println() and it works fine. – Alexander Guyer Oct 05 '14 at 17:04
  • Wow! Thanks a lot for this (incredibly) detailed and huge answer! I'll try these codes out and let you know if my problem is solved. :) – user3658616 Oct 05 '14 at 17:14
  • Hahaha, very nicely written! But it definitely sounds like the OP had trouble understanding the basics of simple functions like Threads, a difficult answer like this is usually not very helpful, regardless of it's effectiveness or functionability. At the very least, when giving answers like this, it is best to explain everything you did – DreadHeadedDeveloper Oct 05 '14 at 17:21
  • Haha yeah I wrote the first part with the Thread.sleep() and then decided to try to teach the preferred way. I even purposely put in bold that the second way is definitely not necessary to accomplish something so simple... At the same time it was good practice for me to write the deltaTime calculator way :D. @user3658616, when you say it didn't work, did you try the first way? All it is doing is cycling through each character of "message" in the for loop and adding it to the labelMessage, and then sleeping in between. (and of course you have to set the label text equal to it each time.) – Alexander Guyer Oct 05 '14 at 21:20
  • Oh oh oh I think I know what you did... The code I posted wasn't the whole thing, but merely conceptual. You still had to create the JFrame yourself and add the JLabel to it. Just making sure that was clear. – Alexander Guyer Oct 05 '14 at 21:22
0

I'm unable to use Thread.sleep(x) or wait(): java.lang.InterruptedException; must be caught or declared to be thrown

try {
    Thread.sleep(100);
} catch(InterruptedException ex) {
    Thread.currentThread().interrupt();
}
Community
  • 1
  • 1
0

You may use this code for doing so. Simply put a thread to print the text onto a jLabel.

             new Thread(new Runnable() {
                @Override
                public void run() {
                    String x="";   
                    String txt="Hello this is a sample text. Let us see how this works.";
                    for(int i=0;i<txt.length();i++){
                        try {

                                jLabel1.setText(x=x+txt.charAt(i));

                                Thread.sleep(100);
                            } catch(InterruptedException ex) {
                                Thread.currentThread().interrupt();
                            }
                    }
                }
            }).start();
Kunjan Thadani
  • 1,660
  • 3
  • 18
  • 26
-1

How about this?

import javax.swing.Timer;
import java.awt.event.*;
import javax.swing.JFrame;
import javax.swing.JLabel;


public class DelayText
{

   public String example = "As you can see, this sentence is being printed out a character at a time.";
   public String transfer = "";
   public Timer t;
   public int i = 0;
   public JFrame f;
   public JLabel l;

   public DelayText()
   {



      f = new JFrame("Example");   
      l = new JLabel();

      f.add(l);

      f.setSize(450, 200);

      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


      f.setVisible(true);


      TimerListener tl = new TimerListener();

      t = new Timer(100, tl);

      t.start();




   }

   public static void main(String[] args)
   {

      DelayText d = new DelayText();

   }

   private class TimerListener implements ActionListener
   {

      public void actionPerformed(ActionEvent e)
      {

         if(i < example.length())
         {

            transfer += (example.charAt(i));
            l.setText(transfer);
            i++;



         }

         if(i >= example.length())
         {

            t.stop();

         }



      }

   }

}

I am using the timer to create a delay between each character outputted on the JFrame. I noticed a lot of these other ones were a bit more complex, thought this might make things a bit easier to understand.