« Return to Thread: Clock help

Re: Clock help

by Gregg Wonderly-2 :: Rate this Message:

Reply to Author | View in Thread

Petr Dvorak wrote:

> Do you mean something like this (the simplest/likely-dumbest
> implementation possible)? You might play with the appearance, output
> format, etc... The key portion of code:
>
>    public NewJFrame() {
>        initComponents();
>        jLabel1.setText(Calendar.getInstance().getTime().toString());
>
>        _iTimer = new Timer(true);
>        _iTimer.scheduleAtFixedRate(new TimerTask() {
>
>            @Override
>            public void run() {  
> jLabel1.setText(Calendar.getInstance().getTime().toString());
>            }
>        }, 1000, 1000);
>    }

You must code this with some variant of the following,

             public void run() {
                SwingUtilities.invokeAndLater( new Runnable() { public void run() {
  jLabel1.setText(Calendar.getInstance().getTime().toString());
                } } );
             }

to make sure that you don't futz with the AWT/swing environment?  A non event
thread should never be calling into any GUI component methods!  You could use
invokeAndWait() as well, but that requires handling interrupted exceptions.

Gregg Wonderly

 « Return to Thread: Clock help