我正在制作一个简单的应用程序来截取screenshot.so我使用swing定时器为此。但我有一个问题,当我设置间隔时间为100毫秒它完美的作品。为什么java swing定时器自动停止?
Timer t=new Timer(100, new ActionListener()//this is working
但是,当我设置间隔为1000它不工作。
Timer t=new Timer(1000, new ActionListener()//this is not working
没有错误,但程序会自动terminate.timer不fire.i使用netbeans.i可以看到程序已停止。这是我在控制台中看到。
我想不出我有什么地方错了。或者有我错过了什么?
这是我的代码
public class Screenshot {
Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
private final String s;
int i=0;
public Screenshot() {
SimpleDateFormat sdf=new SimpleDateFormat("M,dd,hh,mm,ss");
s = sdf.format(new Date());
System.out.println(s);
shoot();
System.out.println("CALLED");
}
public final void shoot() {
Timer t=new Timer(1000, new ActionListener() {//not working with 1000 but work with 100
@Override
public void actionPerformed(ActionEvent e) {
try {
i++;
System.out.println(i);
BufferedImage capture = new Robot().createScreenCapture(screenRect);
ImageIO.write(capture, "jpg", new File("C:\\Users\\Madhawa.se\\Desktop\\screenshot\\"+s+"sh"+i+".jpg"));
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
t.start();
}
public static void main(String[] args) {
Screenshot shot=new Screenshot();
}
}
@getlost你真的应该阅读关于线程和Swing并发性的教程。当你编写一个小例子程序来测试它时发生了什么? – 2014-09-30 18:39:23