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

后端 未结 4 1321
青春惊慌失措
青春惊慌失措 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;
    

    }

提交回复
热议问题