如何将JLabel文本更改为x秒 [英] How to change a JLabel text for x Seconds
问题描述
我想在短时间内更改JLabel
文本(有一个计数器,如果有人在文本字段中输入错误的答案,我想显示一个错误的答案"而不是计数器.秒,我想再次显示计数器.)
I want to change the JLabel
text for a short moment (there's a counter and if someone types in the wrong answer in a text field, I want to show a "wrong answer" instead of the counter. After a few seconds I want to show the counter again.)
推荐答案
对于 固定延迟执行 您要使用计时器对象的某些代码,在这种情况下,为
For the fixed-delay execution of some code you want to use a timer object, in this case javax.swing.Timer. Here is a demo that applies to your situation:
public static void main(String[] args) {
SwingUtilities.invokeLater(()->{
JFrame frame = new JFrame();
frame.setLayout(new FlowLayout());
JLabel label = new JLabel("One");
JButton button = new JButton("Ok");
button.addActionListener(e -> {
String oldText = label.getText();
label.setText("Changed");
Timer timer = new Timer(2000, event -> {
label.setText(oldText);
});
timer.setRepeats(false);
timer.start();
});
frame.add(label);
frame.add(button);
frame.pack();
frame.setVisible(true);
});
}
按钮的侦听器更改标签的文本并启动Swing计时器(此处带有2秒的保险丝).一旦计时器超时,它将向其注册的侦听器其发送一个动作事件,在这种情况下,该事件会将文本还原为原始文本.
The listener for the button changes the text of the label and starts a Swing timer (here with a fuse of 2 seconds). Once the timer times out, it sends an action event to its (the timer's) registered listener, which in this case reverts the text to the original one.
这篇关于如何将JLabel文本更改为x秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!