【问题标题】:JPanel not updating CardLayout properly when I use sleep当我使用睡眠时,JPanel 没有正确更新 CardLayout
【发布时间】:2012-03-01 06:52:55
【问题描述】:

我编写了一个使用 CardLayout 的程序。我希望它显示一个 JPanel,然后根据用户的输入显示一个新的 JPanel,暂停 3 秒,然后显示另一个需要用户输入的 JPanel。

需要用户输入的我的 JPanel 工作正常,我所做的调试告诉我,当程序暂停 3 秒时,正在生成“填充”面板(见下文),但只是没有正确呈现。

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);
        }
    }
}

我认为问题出在这段代码中,但我不知道为什么:

    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);
        }

    }

谢谢!

【问题讨论】:

    标签: java swing sleep cardlayout


    【解决方案1】:

    您正在让您的事件调度程序线程等到 3 秒。这将停止响应,并且您的操作事件直到此时才会返回以进行重新绘制。 检查 SwingUtilities invokeLater(),您可以创建一个后台线程并使其休眠 3 秒。唤醒后,您可以使用 swing 实用程序方法编写 UI 更新代码,以便由 EDT 执行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-05
      • 2013-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-14
      相关资源
      最近更新 更多