添加计时器并显示标签文本

sha*_*Hwk 0 java swing timer jlabel

我有一个JLabel.最初我已经为它设置了一些文字.

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

j.setText("Hello");
Run Code Online (Sandbox Code Playgroud)

我只希望文本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");

}
Run Code Online (Sandbox Code Playgroud)

Mad*_*mer 5

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

查看

欲获得更多信息