如何在 x 秒内更改 JLabel 文本
How to change a JLabel text for x Seconds
我想暂时更改 JLabel
文本(有一个计数器,如果有人在文本字段中输入错误答案,我想显示 "wrong answer" 而不是计数器。几秒钟后我想再次显示计数器。)
// change text to error
Thread.sleep(5000); // 5000ms = 5 seconds
// change text to counter
这很容易做到。显然你应该用实际代码替换注释。
使用 paint()
void 之外的变量,告诉 paint()
方法在屏幕上绘制或不绘制计数器。例如,
boolean wrongAnswer = true;
public void paint(Graphics g){
if(b){
g.drawString("Wrong Answer.", x, y);
//It's best to use a timer, see the link provided
}
else{
g.drawString(counter+"", x, y)
}
}
why not to use thread.sleep for no reason, and explain it to a programmer
为 of some code you want to use a timer object, in this case javax.swing.Timer。这是一个适用于您的情况的演示:
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 秒的保险丝)。一旦计时器超时,它会向它的(计时器的)注册侦听器发送一个动作事件,在这种情况下,它将文本恢复为原始文本。
我想暂时更改 JLabel
文本(有一个计数器,如果有人在文本字段中输入错误答案,我想显示 "wrong answer" 而不是计数器。几秒钟后我想再次显示计数器。)
// change text to error
Thread.sleep(5000); // 5000ms = 5 seconds
// change text to counter
这很容易做到。显然你应该用实际代码替换注释。
使用 paint()
void 之外的变量,告诉 paint()
方法在屏幕上绘制或不绘制计数器。例如,
boolean wrongAnswer = true;
public void paint(Graphics g){
if(b){
g.drawString("Wrong Answer.", x, y);
//It's best to use a timer, see the link provided
}
else{
g.drawString(counter+"", x, y)
}
}
why not to use thread.sleep for no reason, and explain it to a programmer
为
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 秒的保险丝)。一旦计时器超时,它会向它的(计时器的)注册侦听器发送一个动作事件,在这种情况下,它将文本恢复为原始文本。