I am currently making this text-based rpg game with a simple GUI. I was happy to find the good start at it but then there is something I stumbled upon that made me stop coding for a while.
If you are making this in console, you could easily use this code to pause the movements of the characters for a while, like:
System.out.println("[enemy]");
Thread.sleep(1000);
System.out.println("The local guard waves his sword and tries to stab you in the back, but you quickly parried and tried for a counterattack but you failed.");
If you are doing this on a JTextArea
, you'd use the setText
but
if you use Thread.sleep
it doesnt work and coding setText
again, would erase the old text and replace it with the new text, so the records of the fight will not be fully displayed on the game. Is there a way to fix this?
You can use append
to append instead of replace. That is the easy part.
The hard part: You have to change your program flow. In Swing there exists a single thread for dispatching GUI events, the event dispatching thread. You should not set the EDT to sleep
or do any other long-running operations in it. This will freeze the GUI, it can't respond to anything and will not repaint.
Instead you should either start a new thread for the logic flow and dispatch operations that have to be executed on the EDT (everything that manipulates the GUI) with SwingUtilities.invokeLater
or, in this case maybe better, SwingUtilities.invokeAndWait
.
Or you should embrace an event driven control flow, e.g. you could use a Timer
to output the second text later.
A program flow that works well with single-threaded console programs is not the right approach for multi-threaded GUI applications (and every GUI application is automatically multi-threaded).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With