0

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");

}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Sharon Watinsan
  • 9,620
  • 31
  • 96
  • 140

1 Answers1

5

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

For more information

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366