在学Timer,一个简单问题,请告诉小弟,谢谢
代码如下,这么不能显示我需要的结果???
import javax.swing.*;
import javax.swing.Timer;
import java.awt.event.*;
public class TestTimer {
public TestTimer() {
}
public static void main(String[] args){
java.awt.event.ActionListener listener = new Class1();
Timer t = new Timer(1000,listener);
t.start();
}
}
class Class1 implements java.awt.event.ActionListener{
public Class1(){
}
public void actionPerformed(ActionEvent event){
System.out.println("hello");
}
}
------解决方案--------------------import javax.swing.*;
import java.awt.event.*;
public class TestTimer {
public TestTimer() {
}
public static void main(String[] args) {
java.awt.event.ActionListener listener = new Class1();
Timer t = new Timer(1000, listener);
t.start();
if (JOptionPane.showConfirmDialog(null, "确定停止该程序么?", "",
JOptionPane.YES_NO_OPTION) == 1) {
System.exit(0);
}
}
}
class Class1 implements java.awt.event.ActionListener {
public Class1() {
}
public void actionPerformed(ActionEvent event) {
System.out.println("hello");
}
}
------解决方案--------------------这样试试,应该是为Timer控件添加TimerTask任务
import java.util.*;
import java.awt.event.*;
public class TestTimer {
public TestTimer() {
}
public static void main(String[] args){
Class1 listener = new Class1();
Timer t = new Timer("show",false);
t.schedule(listener,0,1000);
}
}
Class1 extends TimerTask{
public Class1(){
}
public void run(){
System.out.println("hello");
}
}
------解决方案--------------------那是为了 防止主线程的结束
你也可以用下面代码或其它 可使主线程停下的代码代替
//(程序执行一会后就退出)
try{Thread.sleep(10000);
}catch(Exception e){}