How to update JLabel in Swing?

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

I know how to create a window with text. And I understand how the Timer works (it periodically starts an action). But I can’t figure out how to comb these two things. Should I use this: JLabel label = new JLabel(myMessage); and then using the timer do I need to update myMessage variable?

But I think I need to "force" my window to "update" itself (in order to display the new value stored in "myMessage").

+4
source share
2 answers

I suggest you call the JLabel#setText method every time the content is updated. however, due to the very monotonous nature of Swing, you need to update your widgets in the so-called Dispatch Thread (EDT) event. To do this, call SwingUtilities.invokeLater or SwingUtilities.invokeAndWait in your timer code.

That way, when the text changes due to your setText call, the JLabel events will correctly propagate and the label will be updated correctly.

+7
source

Hi, use the observer pattern. That is, your ui class may be a listener of your timer structure. When your variable changes, call 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 value you should call invokeListeners() invokeListener(){ for(Listener listener :listeners) listener.update(getSecond()); } 

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

+4
source

Source: https://habr.com/ru/post/1304564/


All Articles