« Return to Thread: Clock help

Re: Clock help

by Petr Dvorak :: Rate this Message:

Reply to Author | View in Thread

Gregg Wonderly wrote:

> 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

Thanks for the good remark (suggestion to use of
SwingUtilities.invokeLater) - I said it is simplest and likely-dumbest
implementation possible. I still think that use of my simple code is
good enough for this demo app (the application should do nothing more
that the clock), but generally you are right... P.D.

        _iTimer.scheduleAtFixedRate(new TimerTask() {

            @Override
            public void run() {
                SwingUtilities.invokeLater(new Runnable() {

                    public void run() {
                       
jLabel1.setText(Calendar.getInstance().getTime().toString());
                    }
                });

            }
        }, 1000, 1000);

 « Return to Thread: Clock help