Wednesday, 15 August 2012

java - How to dynamically change JLabel's contents -



java - How to dynamically change JLabel's contents -

the below program, calls jframe's frame.repaint() fill within frame dynamically. on same lines, want have 2 labels( west & east) of frame , have labels dynamically changing. have tried lotta things like, jlabel label.repaint(),label.removeall(),etc, doesn't work. have left code, clean can fill in...

jframe frame=new jframe(); frame.setsize(512, 512); frame.add(image1); frame.setvisible(true); frame.setdefaultcloseoperation(jframe.exit_on_close); start_sum=0; while(true) { frame.repaint(); seek { thread.sleep(sleep_for_each_rotation); } grab (interruptedexception e) { // todo auto-generated grab block e.printstacktrace(); } start_sum+=radian/divide_size; //some calculation stuff if(start_sum>=360) start_sum=0; }

from looks of code, blocking event dispatching thread (edt).

the edt responsible (amongst other things), processing repaint events. means if block edt, nil can repainted.

the other problem have is, should never create or modify ui component thread other edt.

take @ concurrency in swing more details.

the next illustration uses javax.swing.timer, sounds of things, you'll find swing worker more useful

public class testlabelanimation { public static void main(string[] args) { new testlabelanimation(); } public testlabelanimation() { eventqueue.invokelater(new runnable() { @override public void run() { seek { uimanager.setlookandfeel(uimanager.getsystemlookandfeelclassname()); } grab (classnotfoundexception | instantiationexception | illegalaccessexception | unsupportedlookandfeelexception ex) { } jframe frame = new jframe("test"); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.setlayout(new borderlayout()); frame.add(new testpane()); frame.pack(); frame.setlocationrelativeto(null); frame.setvisible(true); } }); } public class testpane extends jpanel { private jlabel left; private jlabel right; public testpane() { setlayout(new borderlayout()); left = new jlabel("0"); right = new jlabel("0"); add(left, borderlayout.west); add(right, borderlayout.east); timer timer = new timer(250, new actionlistener() { @override public void actionperformed(actionevent e) { left.settext(integer.tostring((int)math.round(math.random() * 100))); right.settext(integer.tostring((int)math.round(math.random() * 100))); } }); timer.setrepeats(true); timer.setcoalesce(true); timer.start(); } } }

java swing jframe jpanel jlabel

No comments:

Post a Comment