Re: [問題] 請問,有關paint()執行的順序

看板java作者 (HY)時間19年前 (2006/05/31 22:02), 編輯推噓1(100)
留言1則, 1人參與, 最新討論串2/2 (看更多)
※ 引述《artin (讓我備上吧﹒orz...)》之銘言: : 各位大大,大家好,我是java新手… : 如果有人問過了,對不起,我一定會馬上回來d掉的....>< 先說聲抱歉.... : 我想要把一行字,造成在畫面上移動的樣子 : 那我的想法是,每次更新印出的位置,然後再repaint()一次 : 我的程式碼如下 : import java.applet.Applet; : import java.awt.*; : import java.awt.event.*; : import java.lang.*; : /* : <applet : code = slide.class : width=600 : height=600> : </applet> : */ : public class slide extends Applet implements ActionListene : { : Button button1; : int i=60; : String Sa = "hello java"; : public void init() : { : button1 = new Button("click me"); : add(button1); : button1.addActionListener(this); : } : public void paint(Graphics g) : { : g.drawString(Sa,i,100); : System.out.println("CALL paint()"); : } : public void actionPerformed(ActionEvent e) : { : if(e.getSource() == button1) : { : while(i<160) : { : ++i; : repaint(); : System.out.println(i); : } : } : } : } : 那我想,當按下button後,應該會印出 : CALL paint() : 61 : CALL paint() : 62 : CALL paint() : . : . : CALL paint() : 160 : 可是,實際上卻出現 : 61 : 62 : . : . : . : 160 : CALL paint() : 那這和我原本希望的不一樣,為什麼,它會在for loop的最後一次才會 : 呼叫paint()這個method呢? : 因為我想了一陣子,也沒看過書上提過… : 所以才po上來,請教各位大大 : 謝謝.... 中文 http://www.javaworld.com.tw/jute/post/view ?bid=5&id=33130&tpg=1&ppg=1&sty=1&age=0#33130 英文 http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html 總之因為 Swing Update UI 的動作以及 Event Handler 都是在 Event-Dispatching Thread 裡做 所以你呼叫的repaint()都是排程在actionPerformed Event-Dispatching Thread的狀態 actionPerformed()--->repaint()---->repaint()--->repaint()--->....... 所以actionPerformed執行完才會執行repaint() Event-Dispatching Thread好像會把多餘的動作省略 所以只會執行一次repaint(); 你可以試試在actionPerformed裡加入更花時間的動作 你會發現UI都沒回應了,因為 Update UI 的動作都要等 actionPerformed執行完才會執行 正確的作法是將花時間的動作用new Thread來做, 如此actionPerformed可以立即執行完畢 並繼續下一個在 Event-Dispatching Thread 的 task 換言之,所有花時間的動作都應該使用new Thread 避免在 Event Handler(Event-Dispatching Thread)來做 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.111.79.32

05/31 23:29, , 1F
原來是這樣,謝謝大大,我再多去了解一下thread,感謝..T_T
05/31 23:29, 1F
文章代碼(AID): #14VQ7eNW (java)
文章代碼(AID): #14VQ7eNW (java)