[英]How to add a timer to change text of a JTextPane in java?
I am working on a java program, what I want to implement is once the window loads, the set of text in a JTextPane to change. 我正在研究一个java程序,我想要实现的是一旦窗口加载,JTextPane中的文本集就会改变。 I have the below code that creates the JTextPane; 我有以下代码创建JTextPane;
JTextPane txtpnReady = new JTextPane();
txtpnReady.setText("Ready");
txtpnReady.setEditable(false);
txtpnReady.setBounds(181, 39, 169, 20);
contentPane.add(txtpnReady);
I am unsure of how to add a timer that will change the text of this JTextPane, after 2 seconds, I need it to say Ready once the program loads, then after 2 seconds Steady and then after 2 seconds, Go. 我不确定如何添加一个定时器来改变这个JTextPane的文本,2秒后,我需要它说准备一旦程序加载,然后2秒后稳定然后2秒后,Go。
Thanks. 谢谢。
You may want to take a look to How to Use Swing Timers trail. 您可能需要了解如何使用Swing Timers跟踪。 You can do something like this: 你可以这样做:
Timer timer = new Timer(2000, new ActionListener() {
private String nextText = "Steady";
@Override
public void actionPerformed(ActionEvent e) {
txtpnReady.setText(nextText);
if(!nextText.equals("Go")) {
nextText = "Go";
} else {
((Timer)e.getSource()).stop();
}
}
});
timer.setRepeats(true);
timer.setDelay(2000);
timer.start();
About this: 对这个:
txtpnReady.setBounds(181, 39, 169, 20);
The use of setBounds()
is not a good practice since swing applications must be able to run on different platforms and Look & feels. 使用setBounds()
不是一个好习惯,因为swing应用程序必须能够在不同的平台和Look&feel上运行。 You should let layout managers do their job and avoid the use of setBounds()
and set(Preferred|Maximum|Minimum)Size
. 您应该让布局管理器完成工作,避免使用setBounds()
和set(Preferred|Maximum|Minimum)Size
。
Suggested readings: 建议读数:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.