I try to show some text in my JTextArea
in runtime. But when I use a loop of setText
to show text in order, it only show the text of the last loop
Here is my code:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
for (int i=0;i<10;i++)
jTextArea1.setText("Example "+i);
}
I want it to show "Example 1", "Example 2",..,"Example 9"
. But it only show one time "Example 9
"
Anyone can explain it for me??
setText
does just that, it "sets the text" of field to the value your provide, removing all previous content.What you want is
JTextArea#append
If you're using Java 8, another option might be
StringJoiner
(assuming you want to replace the text each time the
actionPerformed
method is called, but you can still useappend
)Update based on assumptions around comments
I "assume" you mean you want each
String
to be displayed for a short period of time and then replaced with the nextString
.Swing is a single threaded environment, so anything that blocks the Event Dispatching Thread, like loops, will prevent the UI from been updated. Instead, you need to use a Swing
Timer
to schedule a callback at regular intervals and make change the UI on each tick, for example.Have a look at Concurrency in Swing and How to use Swing Timers for more details