“GUI while loop”

僤鯓⒐⒋嵵緔 提交于 2020-01-07 09:21:29

问题


Okay, I have a code that looks like this:

public class Test
{   

private JPanel dummy;

public checker()
{
    dummy = new JPanel();
    dummy.setVisible(false);

    dummy.addComponentListener(new ComponentAdapter()
    {
        @Override
        public void componentShown(ComponentEvent arg0)
        {
            dummy.setVisible(false);
            runCheck();
        }           
    });

    runCheck();
}


private void runCheck()
{
    if (a)
    {
        //do something
        dummy.setVisible(true);
    }
}

}

This will create a dummy JPanel and add a component adapter that will fire each time dummy is set to be visible. It works like a while loop, only it makes sure that GUI is updated before it goes into another cycle.

But I need method checker() to return a value once the cycle is broken.

NOTE: This is symplified version of code, I cannot check for condition a, that is not a solution.


回答1:


Use SwingWorker to perform the runCheck() loop in the background. Invoke

dummy.setVisible(false);
worker.execute();

You can call setVisible(true) in done(), as shown here for setEnabled().




回答2:


I figured it out. I can use secondaryLoop. I am unable to explain how it actually works, but it enables me to freeze the program (but the EDT) and, while the code is frozen, add events to the EDT queue which are done immediatley (if EDT isn't busy doing anything else, which, in my case, isn't).

More on topic: link



来源:https://stackoverflow.com/questions/18047297/gui-while-loop

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