添加一个计时器,显示文字标签(Adding a timer and displaying label

2019-07-04 11:09发布

我有一个JLabel。 起初,我已经设置了一些文本。

JLabel j = new JLabel();
// set width height and position

j.setText("Hello");

我只想文本Hello显示5秒钟。 然后我想显示的文本再见。

我怎么能做到这一点。

我的工作方式; 但我知道这是错的,因为它一次只能执行1的if-else块。 我想我需要一个定时器或计数器。 得到这个工作。 救命 ?

long time = System.currentTimeMillis();

if ( time < (time+5000)) { // adding 5 sec to the time
    j.setText("Hello");

} else {
    j.setText("Bye");

}

Answer 1:

Swing是一个事件驱动的环境中,你需要下架的最重要的一个概念是,你必须永远,永远,阻断事件以任何方式(包括调度线程,但不限于,循环,I / O或Thread#sleep

话虽如此,有办法实现你的目标。 最简单的是通过javax.swing.Timer类。

public class TestBlinkingText {

    public static void main(String[] args) {

        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 BlinkPane());
                frame.setSize(200, 200);
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }

        });

    }

    protected static class BlinkPane extends JLabel {

        private JLabel label;
        private boolean state;

        public BlinkPane() {
            label = new JLabel("Hello");
            setLayout(new GridBagLayout());

            add(label);
            Timer timer = new Timer(5000, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent ae) {
                    label.setText("Good-Bye");
                    repaint();
                }
            });
            timer.setRepeats(false);
            timer.setCoalesce(true);
            timer.start();
        }
    }
}

查看

  • 事件调度线程
  • 如何使用Swing计时器

欲获得更多信息



文章来源: Adding a timer and displaying label text