简体   繁体   English

JProgressBar在Try-catch完成之前不会启动

[英]JProgressBar Doesn't Start Until Try-catch finishes

I am writing a program which uses Random.ORG api. 我正在编写一个使用Random.ORG api的程序。 When I click calculate button, JProgressBar starts right after the opeartion is being done and stay freezed until this moment. 当我点击计算按钮时,JProgressBar会在操作完成后立即启动并保持冻结直到此刻。

I tried extra try-catch clauses, if statements and bool-gates. 我尝试了额外的try-catch子句,if语句和bool-gates。 None of them worked, how could I fix it? 他们都没有工作,我怎么能解决它?

kazananiBelirleButon.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                progressBar.setVisible(true);
                progressBar.setIndeterminate(true);

                try {

                    HashMap<String, Object> randoms = randSonuc.generateSignedIntegers(5, 0, 10);
                    System.out.println(randoms.toString());
                    String test = randoms.toString().substring(randoms.toString().indexOf("{r")+1, randoms.toString().indexOf(", da")).replace("random=", "{\"random\":") + "}";


                    System.out.println(tarihiYazdir(test,14));
                    cekilisTarihiTextPane.setText(tarihiYazdir(test,2).toString());
                    sonucPane.setText("\n"+sonuclariYazdir(test,0));



                } catch (RandomOrgSendTimeoutException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (RandomOrgKeyNotRunningError e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (RandomOrgInsufficientRequestsError e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (RandomOrgInsufficientBitsError e1) {
                    System.out.print("lol");
                    e1.printStackTrace();
                } catch (RandomOrgBadHTTPResponseException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (RandomOrgRANDOMORGError e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (RandomOrgJSONRPCError e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (MalformedURLException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        });

Swing is single threaded. Swing是单线程的。 Calling listeners, painting/updating UI all happen on a single thread called the Event Dispatch Thread (EDT). 调用侦听器,绘制/更新UI都发生在称为事件调度线程 (EDT)的单个线程上。

Since you do all your work in the event handler code, the Swing UI cannot be updated until you return from your method ( actionPerformed() ). 由于您在事件处理程序代码中完成所有工作,因此在从方法返回之前无法更新Swing UI( actionPerformed() )。

Read this tutorial: Concurrency in Swing 阅读本教程: Swing中的并发性

What you should do is do your time-consuming work in a separate thread and only do short tasks in the EDT (eg UI updates). 你应该做的是在一个单独的线程中做你耗时的工作,只做EDT中的简短任务(例如UI更新)。

Also check out the SwingWorker class which is designed to perform lengthy GUI-interaction tasks in a background thread. 另请查看SwingWorker类,该类旨在在后台线程中执行冗长的GUI交互任务。

Try using swing worker in your method. 尝试在您的方法中使用swing worker。 Swing Worker 摇摆工人

Here is an example from old version of swing worker. 这是旧版swing工作者的一个例子。 Firs you need to add SwingWorker class to your project: 您需要在项目中添加SwingWorker类:

import javax.swing.SwingUtilities;

/**
 * This is the 3rd version of SwingWorker (also known as
 * SwingWorker 3), an abstract class that you subclass to
 * perform GUI-related work in a dedicated thread.  For
 * instructions on using this class, see:
 *
 * http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html
 *
 * Note that the API changed slightly in the 3rd version:
 * You must now invoke start() on the SwingWorker after
 * creating it.
 */
public abstract class SwingWorker
{

    private Object value;  // see getValue(), setValue()
    private Thread thread;

    /**
     * Class to maintain reference to current worker thread
     * under separate synchronization control.
     */
    private static class ThreadVar
    {

        private Thread thread;

        ThreadVar(Thread t)
        {
            thread = t;
        }

        synchronized Thread get()
        {
            return thread;
        }

        synchronized void clear()
        {
            thread = null;
        }
    }
    private ThreadVar threadVar;

    /**
     * Get the value produced by the worker thread, or null if it
     * hasn't been constructed yet.
     */
    protected synchronized Object getValue()
    {
        return value;
    }

    /**
     * Set the value produced by worker thread
     */
    private synchronized void setValue(Object x)
    {
        value = x;
    }

    /**
     * Compute the value to be returned by the <code>get</code> method.
     */
    public abstract Object construct();

    /**
     * Called on the event dispatching thread (not on the worker thread)
     * after the <code>construct</code> method has returned.
     */
    public void finished()
    {
    }

    /**
     * A new method that interrupts the worker thread.  Call this method
     * to force the worker to stop what it's doing.
     */
    public void interrupt()
    {
        Thread t = threadVar.get();
        if (t != null)
        {
            t.interrupt();
        }
        threadVar.clear();
    }

    /**
     * Return the value created by the <code>construct</code> method.
     * Returns null if either the constructing thread or the current
     * thread was interrupted before a value was produced.
     *
     * @return the value created by the <code>construct</code> method
     */
    public Object get()
    {
        while (true)
        {
            Thread t = threadVar.get();
            if (t == null)
            {
                return getValue();
            }
            try
            {
                t.join();
            }
            catch (InterruptedException e)
            {
                Thread.currentThread().interrupt(); // propagate
                return null;
            }
        }
    }

    /**
     * Start a thread that will call the <code>construct</code> method
     * and then exit.
     */
    public SwingWorker()
    {
        final Runnable doFinished = new Runnable()
        {

            public void run()
            {
                finished();
            }
        };

        Runnable doConstruct = new Runnable()
        {

            public void run()
            {
                try
                {
                    setValue(construct());
                }
                finally
                {
                    threadVar.clear();
                }

                SwingUtilities.invokeLater(doFinished);
            }
        };

        Thread t = new Thread(doConstruct);
        threadVar = new ThreadVar(t);
    }

    /**
     * Start the worker thread.
     */
    public void start()
    {
        Thread t = threadVar.get();
        if (t != null)
        {
            t.start();
        }
    }
}

Then add your logic inside: 然后在里面添加你的逻辑:

SwingWorker worker = new SwingWorker() {
    @Override
    public Object construct() {
        // add your code here
        progressBar.setVisible(true);
        progressBar.setIndeterminate(true);
        // and so on...

        return 0;
    }
};
worker.start();

So the end resuld should look like this (Note that this is untested code): 所以结果应该是这样的(请注意,这是未经测试的代码):

kazananiBelirleButon.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                SwingWorker worker = new SwingWorker() {

                    @Override
                    public Object construct() {
                        progressBar.setVisible(true);
                        progressBar.setIndeterminate(true);

                        try {

                            HashMap<String, Object> randoms = randSonuc.generateSignedIntegers(5, 0, 10);
                            System.out.println(randoms.toString());
                            String test = randoms.toString().substring(randoms.toString().indexOf("{r")+1, randoms.toString().indexOf(", da")).replace("random=", "{\"random\":") + "}";

                            System.out.println(tarihiYazdir(test,14));
                            cekilisTarihiTextPane.setText(tarihiYazdir(test,2).toString());
                            sonucPane.setText("\n"+sonuclariYazdir(test,0));

                        } catch (RandomOrgSendTimeoutException e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        } catch (RandomOrgKeyNotRunningError e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        } catch (RandomOrgInsufficientRequestsError e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        } catch (RandomOrgInsufficientBitsError e1) {
                            System.out.print("lol");
                            e1.printStackTrace();
                        } catch (RandomOrgBadHTTPResponseException e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        } catch (RandomOrgRANDOMORGError e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        } catch (RandomOrgJSONRPCError e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        } catch (MalformedURLException e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        } catch (IOException e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        }
                    }
                     return 0;
                }
            };
            worker.start();
        });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM