问题描述
我正在编写一个Java swt应用程序来处理服务器日志文件,并生成带有一些分析的Excel工作表,这样做没有问题.
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.
这是代码的基本流程.用户使用directoryDialog选择日志文件,然后按开始按钮.单击该按钮时,将执行以下代码.
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();
}
});
}
在实际处理文件的类中,有一个简单的while循环,该循环一直循环到到达文件末尾为止.从文件中读取每一行后,我调用了一种更新进度条的方法.
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()是一种简单的方法,可计算读取文件的百分位数
getProgress() is a simple method which calculates percentile of the file read
(read/total)*100
以上程序正在运行.我得到了预期的结果.进度条更新,但gui变得无响应.我不能移动窗户.我无法单击关闭按钮.
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.
我尝试使用swing worker和display.asyncExec()
I tried using swing worker and display.asyncExec()
推荐答案
SWT文档明确指出 ProgressBar.setSelection()
当未从UI线程调用时,将引发异常(ERROR_THREAD_INVALID_ACCESS
).这意味着您要么在代码中的某个地方吞下异常,要么上面的代码在UI线程中运行.
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.
有一个片段,其中显示了如何从线程更新ProgressBar
:
display.asyncExec(new Runnable() {
@Override
public void run() {
if (bar.isDisposed ())
return;
bar.setSelection(getProgress);
}
});
这篇关于从线程更新进度条时,SWT窗口无响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!