JFrame freezes while running the code continuously

2020-03-31 07:21发布

I have problem while working with JFrame, which get freezes while running the code continuously. Below is my code:

  1. On clicking on btnRun, I called the function MainLoop():

    ActionListener btnRun_Click = new ActionListener() {
    
        @Override
        public void actionPerformed(ActionEvent e) {
            MainLoop();
        }
    };
    
  2. Implementation of MainLoop():

    void MainLoop()
    {
        Hopper = new CHopper(this);
        System.out.println(Hopper);
        btnRun.setEnabled(false);
        textBox1.setText("");
        Hopper.getM_cmd().ComPort = helpers.Global.ComPort;
        Hopper.getM_cmd().SSPAddress = helpers.Global.SSPAddress;
        Hopper.getM_cmd().Timeout = 2000;
        Hopper.getM_cmd().RetryLevel = 3;
    
    
        System.out.println("In MainLoop: " + Hopper);
    
        // First connect to the validator
        if (ConnectToValidator(10, 3))
        {
            btnHalt.setEnabled(true);
            Running = true;
    
            textBox1.append("\r\nPoll Loop\r\n"
                    + "*********************************\r\n");
        }
    
        // This loop won't run until the validator is connected
        while (Running)
        {
            // poll the validator
            if (!Hopper.DoPoll(textBox1))
            {
                // If the poll fails, try to reconnect
                textBox1.append("Attempting to reconnect...\r\n");
                if (!ConnectToValidator(10, 3))
                {
                    // If it fails after 5 attempts, exit the loop
                    Running = false;
                }
            }
            // tick the timer
                    // timer1.start();
            // update form
            UpdateUI();
            // setup dynamic elements of win form once
            if (!bFormSetup)
            {
                SetupFormLayout();
                bFormSetup = true;
            }
    
        }
    
        //close com port
        Hopper.getM_eSSP().CloseComPort();
    
        btnRun.setEnabled(true);
        btnHalt.setEnabled(false);
    }
    
  3. In the MainLoop() function, the while loop is running continuesly until the Running is true problem is that if i want to stop that while loop i have to set Running to false which is done at another button btnHalt:

    ActionListener btnHalt_Click = new ActionListener() {
    
        @Override
        public void actionPerformed(ActionEvent e) {
            textBox1.append("Poll loop stopped\r\n");
            System.out.println("Hoper Stopped");
            Running = false;
        }
    };
    

but btnHalt is not responding, whole frame is get freeze, also not showing any log in the textarea.

1条回答
家丑人穷心不美
2楼-- · 2020-03-31 08:01

Swing is a single thread framework. That is, there is a single thread responsible for dispatching all the events to all the components, including repaint requests.

Any action which stops/blocks this thread will cause your UI to "hang".

The first rule of Swing, NEVER run any blocking or time consuming tasks on the Event Dispatching Thread, instead, you should use a background thread.

This runs you smack into the second rule of Swing. Never create, modify or interact with any UI component outside of the EDT.

There are a number of ways you can fix this. You could use SwingUtilities.invokeLater or a SwingWorker.

SwingWorker is generally easier, as it provides a number of simple to use methods that automatically re-sync there calls to the EDT.

Take a read through Concurrency in Swing

Updated

Just so you understand ;)

Your MainLoop method should not be executed within the context of the EDT, this is very bad.

Also, you should not be interacting with any UI component from any thread other the then the EDT.

查看更多
登录 后发表回答