2014-02-20 14 views
1

我想暂停执行Swing程序达指定的时间。自然,我使用的第一件事是Thread.sleep(100)(因为我是一个noob)。然后我知道我的程序不是线程安全的,所以我决定使用Timer和其他程序员的一些建议。问题是我无法从我可以学习如何延迟线程的地方获得任何来源,使用Timer。他们大多数使用Timer来延迟执行。请帮我解决这个问题。我在下面提供了一个可编译的代码片段。使用计时器暂停程序执行

import javax.swing.*; 
import java.awt.*; 

public class MatrixBoard_swing extends JFrame{ 

    public static void main(String[] args){ 
     SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
      MatrixBoard_swing b = new MatrixBoard_swing();  
      } 
     }); 
    } 

    MatrixBoard_swing(){ 
     this.setSize(640, 480); 
     this.setVisible(true); 
     while(rad < 200){ 
      repaint(); 
      rad++; 
      try { 
       Thread.sleep(100); 
      } catch (InterruptedException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

     } 
    } 

    int rad = 10; 

    public void paint(Graphics g){ 
     super.paint(g); 
     g.drawOval(400-rad, 400-rad, rad, rad); 
    } 

} 

编辑:我的一个定时器实现审判(请告诉我,如果这是错误的):

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

public class MatrixBoard_swing extends JFrame implements ActionListener{ 

    Timer timer; 

    public static void main(String[] args){ 
     SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
      MatrixBoard_swing b = new MatrixBoard_swing();  
      } 
     }); 
    } 

    MatrixBoard_swing(){ 
     this.setSize(640, 480); 
     this.setVisible(true); 
     timer = new Timer(100, this); 
     timer.start(); 
    } 

    int rad = 10; 

    public void paint(Graphics g){ 
     super.paint(g); 
     g.drawOval(400-rad, 400-rad, rad, rad); 
    } 

    @Override 
    public void actionPerformed(ActionEvent arg0) { 
     repaint(); 
     rad++; 
     if(rad >= 200){ 
      timer.stop(); 
     } 
    } 
+1

您仍然在Swing事件线程上调用'Thread.sleep(...)'。我认为我们已经在你的[先前的类似问题]中解决了这个问题(http://stackoverflow.com/questions/21800147/repaint-is-not-functioning-properly-as-required)。是什么赋予了? –

+4

*“使用计时器暂停程序执行”*请暂停GUI渲染? GUI做了一些长时间的运行操作?允许用户输入?请注意,while(rad <200){... Thread.sleep(100);'表示在GUI中渲染动画时常见的经典错误。 –

+0

我无法理解如何使用计时器。你建议我提供一个简单的,可编译的代码。所以我在这里发布。 –

回答

2

所以不是...

while(rad < 200){ 
    repaint(); 
    rad++; 
    try { 
     Thread.sleep(100); 
    } catch (InterruptedException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 

你只需要打开附近有一座小逻辑...

Timer timer = new Timer(1000, new ActionListener() { 
    public void actionPerformed(ActionEvent evt) { 
     rad++; 
     if (rad < 200) { 
      repaint(); 
     } else { 
      ((Timer)evt.getSource()).stop(); 
     } 
    } 
}); 
timer.start(); 

基本上,Timer将作为Thread.sleep(),但以一种不会破坏用户界面的好方式,但会允许您在执行之间注入延迟。每次它执行时,你需要增加你的价值,测试“停止”条件,否则更新...

看看How to Use Swing Timers和其他3,800问题关于这个问题...