Java暂停程序执行

时间:2012-10-30 02:50:01

标签: java sleep

我有一个更新部分用户界面的方法。调用此方法后,我希望整个程序休眠1秒钟。我不希望在此期间运行任何代码,只需暂停整个执行。实现这一目标的最佳方式是什么?

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

1 个答案:

答案 0 :(得分:1)

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

enter image description here

此示例将每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();
        }

    }

}

您还可以查看展示相同想法的How can I make a clock tick?