java - Mechanisms of setText() in JTextArea? -
i try show text in jtextarea
in runtime. when use loop of settext
show text in order, show text of last loop here code:
private void jbutton1actionperformed(java.awt.event.actionevent evt) { (int i=0;i<10;i++) jtextarea1.settext("example "+i); }
i want show "example 1", "example 2",..,"example 9"
. show 1 time "example 9
"
anyone can explain me??
settext
that, "sets text" of field value provide, removing previous content.
what want jtextarea#append
if you're using java 8, option might stringjoiner
stringjoiner joiner = new stringjoiner(", "); (int = 0; < 10; i++) { joiner.add("quang " + i); } jtextarea1.settexy(joiner.tostring());
(assuming want replace text each time actionperformed
method called, can still use append
)
update based on assumptions around comments
i "assume" mean want each string
displayed short period of time , replaced next string
.
swing single threaded environment, blocks event dispatching thread, loops, prevent ui been updated. instead, need use swing timer
schedule callback @ regular intervals , make change ui on each tick, example.
import java.awt.borderlayout; import java.awt.eventqueue; import java.awt.event.actionevent; import java.awt.event.actionlistener; import javax.swing.jbutton; import javax.swing.jframe; import javax.swing.jpanel; import javax.swing.jscrollpane; import javax.swing.jtextarea; import javax.swing.timer; import javax.swing.uimanager; import javax.swing.unsupportedlookandfeelexception; public class test { public static void main(string[] args) { new test(); } public test() { eventqueue.invokelater(new runnable() { @override public void run() { try { uimanager.setlookandfeel(uimanager.getsystemlookandfeelclassname()); } catch (classnotfoundexception | instantiationexception | illegalaccessexception | unsupportedlookandfeelexception ex) { ex.printstacktrace(); } jframe frame = new jframe("testing"); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.add(new testpane()); frame.pack(); frame.setlocationrelativeto(null); frame.setvisible(true); } }); } public class testpane extends jpanel { private string[] messages = { "example 1", "example 2", "example 3", "example 4", "example 5", "example 6", "example 7", "example 8", "example 9", }; private jtextarea ta; private int index; private timer timer; public testpane() { setlayout(new borderlayout()); ta = new jtextarea(1, 20); add(new jscrollpane(ta)); jbutton btn = new jbutton("start"); btn.addactionlistener(new actionlistener() { @override public void actionperformed(actionevent e) { if (timer.isrunning()) { timer.stop(); } index = 0; timer.start(); } }); add(btn, borderlayout.south); timer = new timer(500, new actionlistener() { @override public void actionperformed(actionevent e) { if (index < messages.length) { ta.settext(messages[index]); } else { timer.stop(); } index++; } }); } } }
have @ concurrency in swing , how use swing timers more details
Comments
Post a Comment