Java: setText GUI code in a text RPG game

I am currently making this text based RPG game with a simple graphical interface. I was happy to find a good start in it, but then I stumbled upon something and I stopped coding a bit.

If you do this on the console, you can easily use this code to pause the movement of characters for a while, for example:

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 do this on JTextArea , you must use setText , but if you use Thread.sleep , it will not work and will not encode setText , erase the old text and replace it with new text, so the battle records will not be fully displayed in the game. Is there any way to fix this?

+4
source share
4 answers

for the setText part, you must have a variable that will hold the text, and when you want to add a line, you add it and set the text again:

 String text ="[enemy]"; textfield.setText(text); text+= "\nblablabla .."; textfield.setText(text); 

UPDATE:

Some of them suggest using the append method, which is relatively good. Sometimes in the game you would like to add and replace all the text (a new conversation with the character), I would recommend something like this:

 textfield.setText("[enemy]\n"); textfield.append("blablabla"); //When someone else wanna talk: thread.Sleep(1000); textfield.setText("[me]\n"); textfield.append("moreblablabla"); 
+2
source

You can use append to add instead of replacing. This is the easy part.

The hard part: you need to change the program flow. In Swing, there is one thread for dispatching GUI events, an event dispatch thread. You should not set EDT to sleep or perform any other lengthy operations in it. This will freeze the graphical interface, it will not be able to answer anything and will not be redrawn.

Instead, you should either start a new thread for the logical threads and send operations that must be performed on the EDT (anything that manipulates the GUI) using SwingUtilities.invokeLater or, in this case, perhaps better, SwingUtilities.invokeAndWait .

Or you should take an event-driven managed thread, for example. you can use Timer to display the second text later.

A program thread that works well with single-threaded console programs is not suitable for multi-threaded GUI applications (and each GUI application is automatically multi-threaded).

+5
source

You can also use the append () function. See JavaDoc .

 jTextField.append("Foo\n"); jTextField.append("Bar\n"); 
+1
source

You can use append() instead of setText() . The append() method will add new text to the end of the old text.

+1
source

Source: https://habr.com/ru/post/1397266/


All Articles