[英]Java pause program execution
I have a method that updates part of the user interface. 我有一种更新部分用户界面的方法。 After this method is called I want the entire program to sleep for say 1 second. 调用此方法后,我希望整个程序休眠1秒钟。 I do not want to run any code during this time, just simply pause the entire execution. 我不想在这段时间内运行任何代码,只需暂停整个执行过程即可。 What would be the best way of achieving this? 实现这一目标的最佳方法是什么?
My reason is this, I am updating the GUI quite a bit and I want the user to see the change before the next change is made. 我的原因是,我正在相当大量地更新GUI,并且希望用户在进行下一个更改之前先看到更改。
If you want the updates to be spaced out, you've better of using something like a javax.swing.Timer
. 如果要间隔更新,最好使用javax.swing.Timer
类的东西。 This will allow to schedule regular updates without causing the UI to look like it's crashed/hung. 这将允许安排定期更新,而不会导致UI看起来像崩溃/挂起。
This example will update the UI every 250 milli seconds 本示例将每250毫秒更新一次UI
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();
}
}
}
You can also have a look at How can I make a clock tick? 您还可以查看如何进行时钟滴答? which demonstrates the same idea 证明了同样的想法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.