java - How to put two different tasks in Threads -
i have following code. in code have image moves left right , button has event. want put these both tasks in threads. can work properly. problem code button event not work until reaches right point.
import java.awt.*; import java.awt.event.*; import javax.swing.*; class myimage extends jframe implements actionlistener { static int xpixel = 20; image myimage, offscreenimage; graphics offscreengraphics; jpanel p = new jpanel(); button btn = new button("bun"); jframe f = new jframe(); public myimage() { myimage = toolkit.getdefaulttoolkit().getimage("mywineshoplogo.jpg"); setextendedstate(jframe.maximized_both); this.setdefaultcloseoperation(jframe.exit_on_close); setvisible(true); add(p); p.add(btn); moveimage(); btn.addactionlistener(this); } public void update(graphics g) { paint(g); } public void paint(graphics g) { int width = getwidth(); int height = getheight(); if (offscreenimage == null) { offscreenimage = createimage(width, height); offscreengraphics = offscreenimage.getgraphics(); } // clear off screen image offscreengraphics.clearrect(0, 0, width + 1, height + 1); // draw image off screen offscreengraphics.drawimage(myimage, xpixel, 10, this); // draw image off screen // show off screen image g.drawimage(offscreenimage, 0, 0, this); // show off screen image } void moveimage() //left right move { thread hilo = new thread() { public void run() { try { (int = 0; < 530; i++) { xpixel += 1; repaint(); // sleep bit animation try { thread.sleep(4); } /* pause 50 milliseconds */ catch (interruptedexception e) { system.err.println("sleep exception"); } } } //try catch (exception ex) { // something... } } }; hilo.start(); } /* void moveimg() // right left move { (int = 529; > 0; i--) { if (i == 1) { moveimage(); } xpixel -= 1; repaint(); // sleep bit animation try { thread.sleep(40); } // pause 50 milliseconds catch (interruptedexception e) { system.err.println("sleep exception"); } } } */ public void actionperformed(actionevent ae) { try { if (ae.getsource() == btn) { p.setbackground(color.red); } } catch (exception e) { system.out.println("error"); } } public static void main(string args[]) { myimage me = new myimage(); } }
whenever write thread.sleep in gui code, stop , introduce task scheduled on swing's timer. need code: schedule each update separate scheduled task on timer. timer quite simple , straightforward use, see example this official oracle tutorial.
Comments
Post a Comment