问题
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.)
回答1:
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);
});
}
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.
回答2:
Use a variable from outside your paint()
void, to tell your paint()
method to draw over or not draw the counter on the screen. For example,
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
回答3:
// change text to error
Thread.sleep(5000); // 5000ms = 5 seconds
// change text to counter
This a easy how you could do it. Obviously you should replace the comments with actual code.
来源:https://stackoverflow.com/questions/58357255/how-to-change-a-jlabel-text-for-x-seconds