Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

I know how to generate a window with text. And I understand how Timer works (it starts an action periodically). But I cannot figure out how to combing this two things. Should I use that: JLabel label = new JLabel(myMessage); and then with timer I need to update the "myMessage" variable?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
776 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...