在进行开发的过程中,经常看到很多软件安装的时候会显示进度,在取消的时候线程也随着取消。所以我们将要进行怎样用线程对进度条进行控制。
当单击“开始”按钮时,创建一个线程;当单击取消按钮时,可以结束线程,这样就达到了对线程的控制,不会让线程自生自灭了。
先上图:
关键代码如下:
package com.wyy.ProgressbarComplex;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.ProgressBar;
import org.eclipse.swt.widgets.Shell;
public class ProgressBarComplex {
//表示线程的状态
static boolean bCancel=false;
public static void main(String[] args){
Display display = new Display();
final Shell shell = new Shell(display);
shell.setText("Progress");
shell.setLayout(new GridLayout(2,false));
//开始和取消按钮
final Button start = new Button(shell, SWT.NONE);
start.setText("开始");
Button cancel = new Button(shell, SWT.NONE);
cancel.setText("取消");
//创建滚动条实例
final ProgressBar progressBar = new ProgressBar(shell, SWT.HORIZONTAL);
GridData data = new GridData();
data.horizontalSpan=2;
data.grabExcessHorizontalSpace = true;
progressBar.setLayoutData(data);
progressBar.setMaximum(100);
progressBar.setMinimum(0);
final int maximun = progressBar.getMaximum();
final int minimus = progressBar.getMinimum();
//为开始按钮注册事件
start.addSelectionListener(new SelectionAdapter() {
//当单击开始按钮时
@Override
public void widgetSelected(SelectionEvent e) {
//首先设置“开始”按钮为不可用状态
start.setEnabled(false);
//创建更新进度条的线程
Runnable runnable = new Runnable(){
public void run(){
for(int i = minimus;i
try{
Thread.sleep(100);
}catch (Exception e) {
}
//注意在更新进度条时加上了判断线程状态的条件
shell.getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
if(progressBar.isDisposed())
return;
//如果此时取消了线程,将进度条设置为初始状态
if(bCancel){
progressBar.setSelection(0);
}
progressBar.setSelection(progressBar.getSelection()+1);
}
});
//如果此时取消了线程,结束该循环,这个线程也就结束了
//并重置线程状态
if(bCancel){
bCancel=false;
break;
}
}
}
};
//启动这个线程
new Thread(runnable).start();
}
});
//注册“取消”按钮事件
cancel.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if(!bCancel){
bCancel = true;
start.setEnabled(true);
}
}
});
shell.pack();
shell.open();
while(!display.isDisposed()){
if(!display.readAndDispatch()){
display.sleep();
}
}
display.dispose();
}
}