问题描述
我编写了一个使用 CardLayout 的程序.我希望它显示一个 JPanel,然后根据用户的输入显示一个新的 JPanel,暂停 3 秒,然后显示另一个需要用户输入的 JPanel.
I have written a program which uses CardLayout. I want it to show a JPanel and then, based on the user's input, shows a new JPanel, pause for 3 seconds, and then show another JPanel which requires user input.
我需要用户输入的 JPanel 工作正常,我所做的调试表明,当程序暂停 3 秒时,正在生成填充"面板(见下文),但没有正确呈现.
My JPanel requiring user input works fine, and the debugging I've done has shown me that when the program pauses for 3 seconds, the "filler" panels (see below) are being generated, but just not rendered properly.
class sylBetween extends JPanel{
sylBetween(boolean response, String fileName){
super();
setSize(1365,725);
JLabel cross = new JLabel("+");
JLabel display;
boolean feedback = myParticipant.getFeedbackTF();
if(feedback){
String v = syllogism.getSyllValidity(fileName);
if(v.equals("V")&&response==true||v.equals("I")&&response==false){
display=new JLabel("Correct");
}
else{
display=new JLabel("Incorrect");
}
add(display);
}
else{
add(cross);
}
}
}
我认为问题出在这段代码中,但我不知道为什么:
and I think the problem is in this bit of code, but I can't figure out why:
public void actionPerformed(ActionEvent e) {
String name = s[currentTrial].getFN();
boolean answerTF = false;
if(e.getSource()==s[currentTrial].yes){
answerTF=true;
}
else if(e.getSource()==s[currentTrial].no){
answerTF=false;
}
currentTrial++;
if(currentTrial>=s.length){
cards.show(this, "end");
}
else{
add(new sylBetween(answerTF,name), "b"+currentTrial);
this.revalidate();
cards.show(this, "b"+currentTrial);
try {
Thread.sleep(3000);
} catch (InterruptedException e1) {
System.err.println(e1);
}
cards.show(this,"Card"+currentTrial);
}
}
谢谢!
推荐答案
您正在让事件调度程序线程等待 3 秒.这将停止响应,并且您的操作事件直到此时才会返回以进行重新绘制.检查 SwingUtilities invokeLater(),您可以创建一个后台线程并使其休眠 3 秒.唤醒后,使用 Swing 实用程序方法,您可以编写 UI 更新代码,以便由 EDT 执行.
You are making your event dispatcher thread wait till 3 second. This will stop the response and your action event will not return back till this time to do repainting.Check SwingUtilities invokeLater(), you can create a background thread and make it sleep for 3 second. once it awake , using swing utility methods you can write your UI updation code such that it will be executed by EDT.
这篇关于当我使用睡眠时 JPanel 没有正确更新 CardLayout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!