-1

我需要在这个程序中暂停一下我正在尝试做的事情。我在 a 中显示一些文本Java Swing JFrame,重新绘制显示它,我等待 1.5 秒,然后更改文本。

基本上,我从这个开始:

statusLabel.setText(s);    
appFrame.repaint();
Thread.sleep(1500);
statusLabel.setText(y);
appFrame.repaint();

但这不起作用。Thread.sleep()将在重绘完成之前调用,这意味着 s 永远不会显示。我阅读了很多不应该Thread.sleep()在 Swing 应用程序中使用的地方,因为它会暂停所有线程,甚至是尝试重新绘制的线程,并且要暂停由actionPerformed()您触发的某些内容需要使用 Java Swing Timer。

这一切都很好,只是我找不到一个地方可以对它们的工作方式提供一个体面的解释。因为,据我所知,计时器专门用于在计时器上重复事件。我只想在 2 次重绘之间延迟 1.5 秒。

我试过这样做...

statusLabel.setText(s);    
appFrame.repaint();

Timer timer = new Timer(1500, new ActionListener()
{
    public void actionPerformed(ActionEvent ae)
    {

    }
});

timer.setInitialDelay(1500);
timer.setRepeats(false);
timer.start();

statusLabel.setText(y);
appFrame.repaint();

...在其 actionPerformed 事件中添加一个具有 1.5 秒初始延迟、无重复和无主体的计时器,因此它实际上只等待 1.5 秒,但它没有工作。

4

2 回答 2

3

正如您的示例中编码的那样,看起来计时器会“工作”,因为该actionPerformed方法是空的,所以它什么也不做。您可能会认为会timer.start()阻塞并等待计时器触发,但实际上它会立即返回。定时器的工作方式是定时器的actionPerformed方法会在它应该被调用的时候从 UI 线程中调用。将代码放在actionPerformed计时器的方法中是定期更新 UI 状态的好方法。

于 2015-01-29T08:26:39.253 回答
1

你有没有试过把你的方法放在statusLabel.setText(y);里面?actionPerformedActionListener

statusLabel.setText(s);    

Timer timer = new Timer(1500, new ActionListener()
{
    public void actionPerformed(ActionEvent ae)
    {
        statusLabel.setText(y);
    }
});

timer.setRepeats(false);
timer.start();

如果这仍然不起作用,请考虑提供一个可运行的示例来演示您的问题。这将导致更少的混乱和更好的反应

更新

你“似乎”想要做的是设置一系列在不同时间触发的事件......而不是使用单独Timer的s,你应该使用一个Timer像循环一样的循环,每次它滴答作响,你检查它是状态并就应该做什么做出一些决定,例如......

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Flashy {

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

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

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public static class TestPane extends JPanel {

        private JLabel flash;
        private JButton makeFlash;

        protected static final Color[] FLASH_COLORS = new Color[]{Color.BLUE, Color.RED, Color.GREEN, Color.YELLOW};
        protected static final int[] FLASH_DELAY = new int[]{1000, 2000, 3000, 4000};
        private int flashPoint;

        public TestPane() {
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;

            flash = new JLabel("Flash");
            flash.setOpaque(true);
            makeFlash = new JButton("Make Flash");

            add(flash, gbc);
            add(makeFlash, gbc);

            makeFlash.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    flashPoint = -1;
                    Timer timer = new Timer(0, new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                            Timer timer = ((Timer)e.getSource());
                            flashPoint++;
                            if (flashPoint < FLASH_COLORS.length) {
                                flash.setBackground(FLASH_COLORS[flashPoint]);
                                System.out.println(FLASH_DELAY[flashPoint]);
                                timer.setDelay(FLASH_DELAY[flashPoint]);
                            } else {
                                flash.setBackground(null);
                                timer.stop();
                                makeFlash.setEnabled(true);
                            }
                        }
                    });
                    timer.setInitialDelay(0);
                    timer.start();                  
                    makeFlash.setEnabled(false);
                }
            });

        }

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

    }

}

现在,如果你想做一些真正花哨的事情,你可以在给定的时间段内设计一系列关键帧。

这意味着您可以更改动画的持续时间,而无需更改任何其他代码,例如...

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Flashy {

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

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

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public static class TestPane extends JPanel {

        private JLabel flash;
        private JButton makeFlash;

        protected static final Color[] FLASH_COLORS = new Color[]{Color.BLUE, Color.RED, Color.GREEN, Color.YELLOW};
        protected static final double[] FLASH_DELAY = new double[]{0, 0.2, 0.4, 0.6};

        public TestPane() {
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;

            flash = new JLabel("Flash");
            flash.setOpaque(true);
            makeFlash = new JButton("Make Flash");

            add(flash, gbc);
            add(makeFlash, gbc);

            makeFlash.addActionListener(new ActionListener() {
                private int playTime = 10000;
                private long startTime;
                private int currentFrame = -1;

                @Override
                public void actionPerformed(ActionEvent e) {
                    startTime = System.currentTimeMillis();

                    Timer timer = new Timer(50, new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                            Timer timer = ((Timer) e.getSource());
                            long now = System.currentTimeMillis();
                            long duration = now - startTime;

                            double progress = (double) duration / (double) playTime;
                            int keyFrame = 0;
                            for (keyFrame = 0; keyFrame < FLASH_DELAY.length; keyFrame++) {

                                double current = FLASH_DELAY[keyFrame];
                                double next = 1d;
                                if (keyFrame + 1 < FLASH_DELAY.length) {
                                    next = FLASH_DELAY[keyFrame + 1];
                                }

                                if (progress >= current && progress < next) {
                                    break;
                                }

                            }

                            if (keyFrame < FLASH_COLORS.length) {

                                flash.setBackground(FLASH_COLORS[keyFrame]);

                            }

                            if (duration >= playTime) {
                                timer.stop();
                                makeFlash.setEnabled(true);
                                flash.setBackground(null);
                            }

                        }
                    });
                    timer.setInitialDelay(0);
                    timer.start();
                    makeFlash.setEnabled(false);
                }
            });

        }

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

    }

}

一个更高级的概念,在这个答案中得到了证明

于 2015-01-29T08:16:37.093 回答