SWT window becomes unresponsive while updating progressbar from a thread

风格不统一 提交于 2019-12-25 04:35:19

问题


I am writing an java swt application to process the server log files and generate a excel sheet with some analytics and I have no issues doing that.

The problem arises when I try to update the progress bar.

Here is a basic flow of the code. The user selects the log file using a directoryDialog and presses a start button. When the button is clicked the following code is executed.

startButton.addMouseListener(new MouseAdapter() {
        public void mouseUp(MouseEvent e) {
            pm.setUserData(ud,progressBar);
            progressBar.getDisplay().asyncExec(new Runnable() {
                        @Override
                        public void run() {
                            pm.startProcessing();
                        }
                    });
}

In the class where the actually processing of the file happens there is simple while loops that loops till it reaches the end of the file. After each line is read from the file I call a method which updates the progress bar.

while ((logEntry = br.readLine()) != null) {
                readSize += logEntry.length() + 1;
                //some long processing logic
                progressBar.setSelection(getProgress());
}

getProgress() is a simple method which calculates percentile of the file read

(read/total)*100

The above program is working. I am getting the expected result. The progress bar updates but the gui becomes unresponsive. I cannot move the window. I cannot click the close button.

I tried using swing worker and display.asyncExec()


回答1:


The SWT documentation clearly states that ProgressBar.setSelection() will throw an exception (ERROR_THREAD_INVALID_ACCESS) when not called from the UI thread. That means you either swallow exceptions somewhere in your code or the code above runs in the UI thread.

There is a snippet which shows how to update a ProgressBar from a thread:

display.asyncExec(new Runnable() {
                    @Override
                    public void run() {
                        if (bar.isDisposed ())
                            return;
                        bar.setSelection(getProgress);
                    }
                });


来源:https://stackoverflow.com/questions/30304309/swt-window-becomes-unresponsive-while-updating-progressbar-from-a-thread

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