I've managed to make a typewriter class that does what I want it to for the most part. It will output the string given to it one character at a time, pausing between each one as if they were typed, pausing a bit longer after periods. The problem I'm having now is that when I use this class it only works once. When I call it twice (or more) it tries to run them at the same time. This causes major problems. So I need a way for the first instance of this class to run and each one that follows to wait "it's turn" before starting. Below is an example of the desired outcome and the current.
import objectdraw.*; // Where active object comes from.
import javax.swing.JTextArea;
public class Typewriter extends ActiveObject {
private JTextArea out;
private String in;
public Typewriter(String s, JTextArea output) {
in = s;
out = output;
start();
}
public void run() {
synchronized(out) {
for(int i=0; i<in.length(); i++) {
out.append(in.substring(i,i+1));
if(in.charAt(i) == '.') {
pause(30);
} else {
pause(200);
}
}
}
}
}
Current:
CODE: new Typewriter("\nHello", output); new Typewriter("\nWorld", output);
CURRENT OUTPUT
HW ol elr ldo
DESIRED OUTPUT
Hello
World
Obviously I left out most of the code from the Typewriter class. If that's really needed I could post it. The javadocs for ActiveObject can be found here. This is how I was taught threads and I'm afraid it may be the problem.
EDIT:
Per an answer below I've added the synchronized(out) line but I'm getting a nullpointerexception when I try to run the code.
Exception in thread "main" java.lang.NullPointerException
at objectdraw.ActiveObject.<init>(ActiveObject.java:239)
at com.caldwellysr.TBA.Typewriter.<init>(Typewriter.java:11)
at com.caldwellysr.TBA.Client.initGame(Client.java:78)
at com.caldwellysr.TBA.Client.<init>(Client.java:66)
at com.caldwellysr.TBA.Client.main(Client.java:24)
The Typewriter line 11 is the header for the constructor. Client line 78 is where I call new Typewriter("Testing", output); where output is a JTextArea Client line 66 is a call to initGame() which has the Typewriter in it Client line 24 is the JFrame constructor.