how to put a timer on a JLabel to update itself every second

后端 未结 4 1320
青春惊慌失措
青春惊慌失措 2020-12-17 04:54

I created a game and in my swing GUI interface I want to put a timer. The way I do this at the moment is have a field with the current time , gotten with System.curren

相关标签:
4条回答
  • 2020-12-17 05:11

    wirite this in Constructor

    ActionListener taskPerformer = new ActionListener() {

                 @Override
    
                public void actionPerformed(ActionEvent evt) {
                   jMenu11.setText(CurrentTime());
                }
            };
    
            Timer t = new Timer(1000, taskPerformer);
            t.start();
    

    And this Write out Constructor

    public String CurrentTime(){

           Calendar cal = new GregorianCalendar();
           int second = cal.get(Calendar.SECOND);
           int min = cal.get(Calendar.MINUTE);
           int hour = cal.get(Calendar.HOUR);
           String s=(checkTime(hour)+":"+checkTime(min)+":"+checkTime(second));
           jMenu11.setText(s);
           return s;
    
       }
    
       public String checkTime(int t){
    String time1;
    if (t < 10){
        time1 = ("0"+t);
        }
    else{
        time1 = (""+t);
        }
    return time1;
    

    }

    0 讨论(0)
  • Have a look at the swing timer class. It allows to setup recurring tasks quite easily.

    0 讨论(0)
  • 2020-12-17 05:27
    new Thread(new Runnable
    {
        public void run()
        {
            long start = System.currentTimeMillis();
            while (true)
            {
                long time = System.currentTimeMillis() - start;
                int seconds = time / 1000;
                SwingUtilities.invokeLater(new Runnable() {
                     public void run()
                     {
                           label.setText("Time Passed: " + seconds);
                     }
                });
                try { Thread.sleep(100); } catch(Exception e) {}
            }
        }
    }).start();
    
    0 讨论(0)
  • 2020-12-17 05:36

    This is how I would set my JLabel to update with time & date.

    Timer SimpleTimer = new Timer(1000, new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e) {
            jLabel1.setText(SimpleDay.format(new Date()));
            jLabel2.setText(SimpleDate.format(new Date()));
            jLabel3.setText(SimpleTime.format(new Date()));
        }
    });
    SimpleTimer.start();
    

    This is then added to your main class and the jlabel1/2/3 get updated with the timer.

    0 讨论(0)
提交回复
热议问题