JPanel not updating CardLayout properly when I use

2019-09-13 06:19发布

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条回答
叼着烟拽天下
2楼-- · 2019-09-13 06:31

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.

查看更多
登录 后发表回答