I have a TextArea that I would like to be able to append characters or words to over a period of time. I tried using Thread.sleep() but then quickly realized this was horribly wrong.
I guess in pseudo-pseudocode
textArea.appendText("hey");
mysteryWaitMethod(500);
textArea.appendText("delayed");
JavaFX does have a timer built in - it's called a Timeline. It's simple, straightforward, and provides extra functionality like Swing's Timer
class, and, most importantly, executes code on the UI thread.
I don't know much about JavaFX directly, but generally you want things that modify the UI executing on the UI thread. That's what this class does... I'd recommend using it over java.util.Timer
(use that for background tasks... not UI ones). When multiple threads try to mess with a UI, bad things tend to happen (which is the reason for these timers).
This post provides a good example of how to use it: https://stackoverflow.com/a/9966213/1515592
Use the javax.swing.Timer
textArea.appendText("hey");
int delay = 500; //milliseconds
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
textArea.appendText("delayed");
}
};
Timer t = new Timer(delay, taskPerformer);
t.setRepeats(false);
t.start();
http://docs.oracle.com/javase/6/docs/api/javax/swing/Timer.html
Or java.util.Timer
new Timer().schedule(
new TimerTask() {
@Override
public void run() {
textArea.appendText("delayed");
}
}, 500);
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Timer.html