[英]Is there a way to pause execution of a running Java program in Eclipse on Macbook Pro?
[英]Java pause program execution
我有一种更新部分用户界面的方法。 调用此方法后,我希望整个程序休眠1秒钟。 我不想在这段时间内运行任何代码,只需暂停整个执行过程即可。 实现这一目标的最佳方法是什么?
我的原因是,我正在相当大量地更新GUI,并且希望用户在进行下一个更改之前先看到更改。
如果要间隔更新,最好使用javax.swing.Timer
类的东西。 这将允许安排定期更新,而不会导致UI看起来像崩溃/挂起。
本示例将每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();
}
}
}
您还可以查看如何进行时钟滴答? 证明了同样的想法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.