簡體   English   中英

Java暫停程序執行

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM