JPanel not updating CardLayout properly when I use sleep

半世苍凉 提交于 2019-12-12 02:48:18

问题


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.

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

    }

Thanks!


回答1:


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.



来源:https://stackoverflow.com/questions/9200072/jpanel-not-updating-cardlayout-properly-when-i-use-sleep

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!