How to update JLabel in Swing?

前端 未结 2 561
日久生厌
日久生厌 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.

    0 讨论(0)
  • 2020-12-19 17:42

    I suggest you to call the JLabel#setText method each time content is updated. however, due to the very monothread nature of Swing, you have to update its widgets in the so-called Event Dispatch Thread (EDT). To do so, consider calling SwingUtilities.invokeLater or SwingUtilities.invokeAndWait in your timer code.

    This way, when text will be changed due to your call of setText, events of JLabel will propagate correctly, and label will be correctly refreshed.

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