定期更改 JButton 文本
我想创建一个 JButton,在第一次单击后定期更改其文本。我对 Swing 库不太熟悉。什么是一个好的起点?我可以在不执行任何操作的情况下更新其文本吗?
谢谢。
I would like to create a JButton that changes its text periodically after the first click. I'm not really familiar with Swing library. What would be a good starting point? May I update its text without an action?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
对于 Swing 中的所有周期性事件,我只建议 javax.swing。 计时器
使用 Timer 的 输出应该是,对于例子
for all periodical events in Swing I only suggest javax.swing.Timer
output by using Timer should be, for example
如果您要在每个固定的时间量更改它,那么您可以使用 Swing Timer 或线程来执行此操作。但为此,您必须至少侦听一个操作,以便可以初始化并启动它。
您还可以使用 java 中的 TimerTask 类。实用程序如下:
If you to change it on every fixed amount of time then you can use Swing Timer or Thread to do this. But for this you have to listen at least one action so that you can initialize and start it.
You can also use TimerTask class from java.util like follow:
我建议您创建一个计时器(此处你可以找到一些文档)
你的类必须扩展动作侦听器ed实现以下方法,该方法允许你更改
JButton
的文本(我称之为“按钮”)。卢卡
I suggest you to create a timer (here you can find some doc)
Your class has to extend action listener ed implements the following method which allow you to change the text of your
JButton
(I called it ``button).Luca
所有其他答案都没有提及如何非定期更新。如果您需要不定期更新,您可以在 GUI 类中创建一个名为 updateButton() 的方法;每次你想要它改变你的文本时就调用它。
只是想我会添加这个以防有人想要不规则地设置它。
All the other answers fail to mention how to update non-periodically. If you need it to update irregularly, you can make a method in your GUI class called something like: updateButton(); and just call that every time you want it to change your text.
Just thought I'd add this in case someone wanted to set it irregularly.
如果您想定期更改它(例如每 5 秒),您可以创建一个新线程,将按钮的文本设置为所需的值并重新绘制它(如果需要)。
If you want to change it periodically (e.g. every 5th second) you could create a new Thread which sets the text of the button to the desired value and repaints it (if necessary).