2014-09-30 40 views
0

我正在制作一个简单的应用程序来截取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可以看到程序已停止。这是我在控制台中看到。

enter image description here

我想不出我有什么地方错了。或者有我错过了什么?

这是我的代码

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();  
    }  
} 

回答

3

这是因为你的主线程退出你的计时器线程甚至开始之前。尝试在创建Screenshot类的实例后,向main()方法添加wait()。

这会阻止你的main()方法退出。在真实的应用程序中,您可能需要一些允许用户退出程序的逻辑,但这会解决您的紧急问题。

这里是我的意思的例子:

import javax.swing.Timer; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 

public class Test { 

    public Test() { 
     start(); 
    } 

    public final void start() { 

     Timer t=new Timer(1000, new ActionListener() { 

      @Override 
      public void actionPerformed(ActionEvent e) { 
       System.out.println("Firing!"); 
      } 
     }); 
     t.start();   
    } 
    public static void main(String... args) { 
     Test shot=new Test(); 

     synchronized(shot){ 
      try { 
       //this causes the Main thread to block, keeping the program running 
       shot.wait(); 
      } 
      catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
     } 
    }  
} 
+0

@getlost你真的应该阅读关于线程和Swing并发性的教程。当你编写一个小例子程序来测试它时发生了什么? – 2014-09-30 18:39:23

1

我会做的第一件事是尝试,这样只有在Swing线程考虑重新编写代码。

编辑:实际上,Swing定时器甚至不应该在没有Swing GUI的情况下使用,因为如果没有GUI,什么都不会使Swing线程继续运行。我会使用java.util.Timer。

+0

我想我不需要摆动timer.may是一个线程,但我不知道为什么它退出 – 2014-09-30 18:26:00

+0

@getlost:显示一个JOptionPane只是为了让Swing线程启动,你会看到代码的作品。 – 2014-09-30 18:31:29