作者HaoYun (HY)
看板java
标题Re: [问题] 请问,有关paint()执行的顺序
时间Wed May 31 22:21:34 2006
※ 引述《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
1F:推 artin:原来是这样,谢谢大大,我再多去了解一下thread,感谢..T_T 05/31 23:29