Adding a timer and displaying label text

你。 提交于 2019-11-26 22:02:11

问题


I have a JLabel. Initially i have set some text to it.

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

j.setText("Hello");

I only want the text Hello to display for 5 seconds. then i want the text Bye to be displayed.

How could i do this.

My workings; but i know it's wrong as it only executes 1 if-else block at a time. I think i will need a timer or a counter. to get this working. Help ?

long time = System.currentTimeMillis();

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

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

}

回答1:


Swing is a event driven environment, one of the most important concepts you need to under stand is that you must never, ever, block the Event Dispatching Thread in any way (including, but not limited to, loops, I/O or Thread#sleep)

Having said that, there are ways to achieve you goal. The simplest is through the javax.swing.Timer class.

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();
        }
    }
}

Check out

  • The Event Dispatch Thread
  • How to Use Swing Timers

For more information



来源:https://stackoverflow.com/questions/13691339/adding-a-timer-and-displaying-label-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!