日期:2014-05-20  浏览次数:20777 次

Timer类在SWT组件中的应用
我写了一个程序如下,
package my_Text3;
import org.eclipse.swt.*;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.graphics.Font;
import java.awt.event.*;
import org.eclipse.swt.widgets.Button;
import javax.swing.Timer;
public class TT {
Canvas canvas; //画布
Shell shell;
Display display;
Button bt; //开始按钮
Timer timer; //时钟控制
public static String s; //写入的字符
int i=1;
TT(){
display=new Display();
shell=new Shell(display);
shell.setBounds(400, 150, 500, 300);
shell.setLayout(null);
bt=new Button(shell,SWT.BORDER);
bt.setBounds(150, 100, 60, 30);
bt.addMouseListener(new MouseListener(){
public void mouseDown(MouseEvent e){
timer=new Timer(1000,new listener()); //按钮事件中新建Timer对象,并开始timer
timer.start();
};
public void mouseDoubleClick(MouseEvent e){}
public void mouseUp(MouseEvent e){}
});
}
public class listener implements ActionListener{ //Timer的动作事件
public void actionPerformed(ActionEvent e){
canvas=new Canvas(shell,SWT.NO_REDRAW_RESIZE);
int i=(int)(Math.random()*6+1);
s=String.valueOf(i); //将数字转换成字符
canvas.addPaintListener(new PaintListener(){ //画出数字
public void paintControl(PaintEvent e){
//e.gc.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_RED));
//e.gc.setLineWidth(5);
//e.gc.drawOval(0, 0, 38, 38);
//e.gc.fillOval(1, 1, 37, 37);
e.gc.setFont(new Font(shell.getDisplay(),"华文行楷",30,SWT.NORMAL));
e.gc.drawString(s, 0, 0);
}
});
i++;
canvas.setBounds(50, 50, 100, 100);
if(i==10){ //画十次就停止Timer
timer.stop();
}
}
}
public static void main(String[] args) {
TT t=new TT();
t.shell.open();
while (!t.shell.isDisposed()) {
if (t.display.readAndDispatch()) t.display.sleep();
}
}

}
问题是不能按照我自己的意思执行,就是在canvas中实现跳动的数字十次,然后停下来,这是为什么啊?

------解决方案--------------------
javax.swing.Timer 是 swing工具类

你看这个 http://www.java2s.com/Code/Java/SWT-JFace-Eclipse/Demonstratesanimation.htm
Display有
Java code
public void timerExec(int, java.lang.Runnable);

------解决方案--------------------
swt 请使用 org.eclipse.swt.widgets.Display 类中的 timerExec 方法 !!!