用滚动的字符示意Task的运行,比较ProgressMonitorDialog
用滚动的字符表示Task的运行,比较ProgressMonitorDialog
JFace中的提供的ProgressMonitorDialog对话框,来表示正在运行的Task,还是比较方便,可设置一共的Task有多少步,现在完成了多少,还有多少没有完成的。
来个例子吧:
public class TT { static ProgressMonitorDialog dialog; public static void main(String[] args) { IRunnableWithProgress runnable = new IRunnableWithProgress() { public void run(IProgressMonitor monitor) { // monitor.beginTask("begin" + "...... ",10); monitor.beginTask("begin" + "...... ",IProgressMonitor.UNKNOWN); monitor.setTaskName("Running cmd XXXX."); int i = 0; while(i++ < 10) { if(monitor.isCanceled()) { monitor.setTaskName("Canceled cmd XXXX."); break; } try { Thread.sleep(1000); monitor.setTaskName("Running cmd XXXX."); monitor.subTask("Running step " +i + " ."); monitor.worked(1); } catch (InterruptedException e) { e.printStackTrace(); } } monitor.done(); } }; try { dialog = new ProgressMonitorDialog(null); dialog.run(true, true, runnable); } catch (Exception e2) { e2.printStackTrace(); } } }
使用IProgressMonitor.UNKNOWN参数,是不知道Task有多少步,Dialog是程序级的对话框,也就模式对话框了。
有的时候想搞一些特别的东东来表示程序中有Task正在运行,这里采用滚动的标记字符来表示Task的运行:
例子:
public class Tsdf { public static Timer t; static Display display = Display.getDefault(); public static void main(String[] args) { Shell shell = new Shell(); shell.setBounds(10,10,150,150); shell.setLayout(new RowLayout(SWT.VERTICAL)); final Label l = new Label(shell, SWT.NONE); l.setText("Running"); final String s = "<<<" + l.getText(); final int[] index = new int[]{0}; Button brun = new Button(shell, SWT.NONE); brun.setText("run"); Button bstop = new Button(shell, SWT.NONE); bstop.setText("stop"); brun.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { if(t != null) { return; } t = new Timer(true); t.scheduleAtFixedRate(new TimerTask() { public void run() { System.out.println("running time " + System.currentTimeMillis()); display.asyncExec(new Runnable() { public void run() { index[0] = (index[0]<3)?index[0]+1:0; if(!l.isDisposed()) { l.setText(s.substring(index[0], s.length()-3+index[0])); } } }); } }, 0, 300); } }); bstop.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { if( t == null) return; t.cancel(); t = null; l.setText("stop"); System.out.println("Stop time " + System.currentTimeMillis()); } }); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); } }
结果:
运行的效果,label中“<<<Runn”,“<<Runni”,“<Runnin”,“Running”交替出现,给人一种动态的效果。
1 楼
lizhensan
2011-09-10
为什么我的进度条不懂呢?拷贝你的代码
2 楼
xmind
2011-09-22
是代码一还是代码二?
有没有import对?
有没有import对?
引用
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;