如何在java中发生程序流时冻结我的jframe

时间:2016-05-04 20:02:26

标签: java user-interface jframe freeze

所以我有一个用Java制作的小谜题,让我们说这个谜题上还有按钮代表这个谜题。有一种解决方法,点击一系列按钮查找解决方案",解决它需要大约1分钟,所以只需点击一下按钮

在这一分钟内,您注意到计算机点击按钮,因为它在程序流程中改变颜色和形状,我想知道是否有办法在调用solve()方法之前冻结jframe然后当方法结束时解冻到解决方案?

1 个答案:

答案 0 :(得分:0)

我对你的要求有点困惑,但我建议使用这段代码来做我认为你要求的事情

private static boolean solveDone = false; //This should go in a the class, not here.

    //Create a new thread to handle processes while the JFrame is frozen
    SwingUtilities.invokeLater(new Thread(){
        public void run(){
            //Code to run while the JFrame is frozen should be put here.
            main.solveDone = true;
        }
    });

    //Sleep the program until the process is done.
    try{
        while(!solveDone) {
            Thread.sleep(10); //Interval in milliseconds to check if the puzzle is done goes here.
        }
        solveDone = false;
    }catch(InterruptedException e){
        e.printStackTrace();
        System.exit(-1);
    }

    //Code to run after solving goes here.

现在,这不是做这种事情的最干净的方法,但我相信它应该有效。

另一方面,如果你确切地知道要花多少时间,你可以这样做。

SwingUtilities.invokeLater(new Thread(){
        public void run(){
            //Code to run while the JFrame is frozen should be put here.
        }
    });

    try{
        Thread.sleep(1000); //The time in milliseconds to sleep the JFrame
    }catch(InterruptedException e){
        e.printStackTrace();
        System.exit(-1);
    }

    //Code to run after solving goes here.