How to update JLabel in Swing?

前端 未结 2 563
日久生厌
日久生厌 2020-12-19 17:14

I am trying to use Swing Timer and I wanted to start from a very simple program. I have a window with text: \"You have n seconds\", where n changes from 10 to 0 every second

2条回答
  •  既然无缘
    2020-12-19 17:24

    Hi bro use observer pattern . That is ,your ui class sould be listener of your timer structure.When your variable changes ,invoke the listeners of your timer which is your ui class.

    //your observer class 
    
    update(Object obj){
    
    label.setText(obj.toString());
    }
    ...
    
    //your observable class
    //when timer changes varible's value  you should call invokeListeners() 
    
    
    invokeListener(){
    
    for(Listener listener :listeners)
    listener.update(getSecond());
    }
    

    I dont know your class and structure.But i used this solution in one of my assignments.

提交回复
热议问题