2012-10-30 199 views
1

我有一个方法可以更新部分用户界面。在这个方法被调用后,我希望整个程序睡1秒。我不想在这段时间运行任何代码,只是简单地暂停整个执行。什么是实现这一目标的最佳方式?Java暂停程序执行

我的理由是,我正在更新GUI,我希望用户在下次更改之前看到更改。

+0

任何具体的理由这样做呢?你可以通过使用Thread.currentThread()。sleep()来使当前线程休眠,但是其他线程也需要为它们获得一个信号让它们睡觉,如果这是你打算做的。 – Vikdor

+0

当你的程序正在睡觉时,你想让GUI做什么?它应该被冻结吗? – Taymon

+0

更新了原因,是的GUI应该被冻结。 –

回答

1

如果您希望将更新间隔开,最好使用类似javax.swing.Timer的东西。这将允许安排定期更新而不会导致UI看起来像崩溃/挂起。

enter image description here

这个例子将更新UI每250毫秒的

public class TestTimerUpdate { 

    public static void main(String[] args) { 
     new TestTimerUpdate(); 
    } 

    public TestTimerUpdate() { 
     EventQueue.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
       } catch (ClassNotFoundException ex) { 
       } catch (InstantiationException ex) { 
       } catch (IllegalAccessException ex) { 
       } catch (UnsupportedLookAndFeelException ex) { 
       } 

       JFrame frame = new JFrame(); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       frame.setLayout(new BorderLayout()); 
       frame.add(new TimerPane()); 
       frame.pack(); 
       frame.setLocationRelativeTo(null); 
       frame.setVisible(true); 
      } 
     }); 
    } 

    protected class TimerPane extends JPanel { 

     private int updates = 0; 

     public TimerPane() { 
      Timer timer = new Timer(250, new ActionListener() { 
       @Override 
       public void actionPerformed(ActionEvent e) { 
        updates++; 
        repaint(); 
       } 
      }); 
      timer.setRepeats(true); 
      timer.setCoalesce(true); 
      timer.start(); 
     } 

     @Override 
     public Dimension getPreferredSize() { 
      return new Dimension(200, 200); 
     } 

     @Override 
     protected void paintComponent(Graphics g) { 
      super.paintComponent(g); 
      Graphics2D g2d = (Graphics2D) g.create(); 
      String text = "I've being updated " + Integer.toString(updates) + " times"; 
      FontMetrics fm = g2d.getFontMetrics(); 

      int x = (getWidth() - fm.stringWidth(text))/2; 
      int y = ((getHeight() - fm.getHeight())/2) + fm.getAscent(); 

      g2d.drawString(text, x, y); 

      g2d.dispose(); 
     } 

    } 

} 

你也可以看看How can I make a clock tick?这表明了同样的想法

+0

感谢您的彻底解答! –