Dynamic Clock in java

后端 未结 7 1091
我在风中等你
我在风中等你 2020-12-16 02:22

I want to implement a clock within my program to diusplay the date and time while the program is running. I have looked into the getCurrentTime() method and

7条回答
  •  无人及你
    2020-12-16 03:02

    You have to update the text in a separate thread every second.

    Ideally you should update swing component only in the EDT ( event dispatcher thread ) but, after I tried it on my machine, using Timer.scheduleAtFixRate gave me better results:

    java.util.Timer http://img175.imageshack.us/img175/8876/capturadepantalla201006o.png

    The javax.swing.Timer version was always about half second behind:

    javax.swing.Timer http://img241.imageshack.us/img241/2599/capturadepantalla201006.png

    I really don't know why.

    Here's the full source:

    package clock;
    
    import javax.swing.*;
    import java.util.*;
    import java.text.SimpleDateFormat;
    
    class Clock {
        private final JLabel time = new JLabel();
        private final SimpleDateFormat sdf  = new SimpleDateFormat("hh:mm");
        private int   currentSecond;
        private Calendar calendar;
    
        public static void main( String [] args ) {
            JFrame frame = new JFrame();
            Clock clock = new Clock();
            frame.add( clock.time );
            frame.pack();
            frame.setVisible( true );
            clock.start();
        }
        private void reset(){
            calendar = Calendar.getInstance();
            currentSecond = calendar.get(Calendar.SECOND);
        }
        public void start(){
            reset();
            Timer timer = new Timer();
            timer.scheduleAtFixedRate( new TimerTask(){
                public void run(){
                    if( currentSecond == 60 ) {
                        reset();
                    }
                    time.setText( String.format("%s:%02d", sdf.format(calendar.getTime()), currentSecond ));
                    currentSecond++;
                }
            }, 0, 1000 );
        }
    }
    

    Here's the modified source using javax.swing.Timer

        public void start(){
            reset();
            Timer timer = new Timer(1000, new ActionListener(){
            public void actionPerformed( ActionEvent e ) {
                    if( currentSecond == 60 ) {
                        reset();
                    }
                    time.setText( String.format("%s:%02d", sdf.format(calendar.getTime()), currentSecond ));
                    currentSecond++;
                }
            });
            timer.start();
        }
    

    Probably I should change the way the string with the date is calculated, but I don't think that's the problem here

    I have read, that, since Java 5 the recommended is: ScheduledExecutorService I leave you the task to implement it.

提交回复
热议问题