2012-07-03 37 views
0

我正在使用窗口生成器設計java應用程序的接口。我需要做的是.. 點擊一個按鈕做兩件事1.做一些後臺任務 2.當這項工作正在進行中時,在新窗口中顯示一個不確定的進度條。 我知道我需要多線程才能完成此任務。swt在新窗口中的不確定進度條

我嘗試了一些教程的幫助,但無法實現這一點。

任何人都可以幫忙嗎?

代碼:從那裏我想打開進度條窗口

public void mouseDown(MouseEvent e) { 
pbar p=new pbar(); 
p.caller(); 
dowork(); 

p.closeprogress() 功能;

} 

ProgressBar類

import org.eclipse.swt.widgets.Display; 


public class pbar { 

protected Shell shell; 

public void pcaller() { 
    try { 
    //System.err.println("Error: " + bod); 


//System.err.println("Error: " + lines); 
     pbar window = new pbar(); 
     window.open(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

/** 
* Open the window. 
*/ 
public void open() { 
    Display display = Display.getDefault(); 
    createContents(); 
    shell.open(); 
    shell.layout(); 
    while (!shell.isDisposed()) { 
     if (!display.readAndDispatch()) { 
      display.sleep(); 
     } 
    } 
} 

/** 
* Create contents of the window. 
*/ 
protected void createContents() { 
    shell = new Shell(); 
    shell.setSize(315, 131); 
    shell.setText("Updating!!! Please Wait"); 

    ProgressBar progressBar = new ProgressBar(shell, SWT.INDETERMINATE); 
    progressBar.setBounds(47, 34, 195, 17); 
// ProgressBar pb2 = new ProgressBar(shell, SWT.HORIZONTAL | 

SWT.INDETERMINATE); 
    // pb2.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); 
} 

public void close() 
{ 
    shell.close(); 
} 
} 

我希望當我打電話p.caller(),會出現進度條。然後,控制應該到達原始程序並執行dowork()方法。當我完成這個方法時,它會調用p.progress.close()。 我不知道爲什麼不理解這個簡單的程序,忘記回答。

回答

4

JFace的使用是否可以接受? 如果是這樣你可以使用ProgressMonitorDialog類。

ProgressMonitorDialog dialog = new ProgressMonitorDialog(parent.getShell()); 
dialog.run(true, true, new SomeTask()); 

... 

class SomeTask implements IRunnableWithProgress { 

    @Override 
    public void run(IProgressMonitor monitor) throws InvocationTargetException, 
      InterruptedException { 
     monitor.beginTask("Doing some task", IProgressMonitor.UNKNOWN); 
     for(int i = 0; i < 1000; i++) { 
      if (!monitor.isCanceled()) 
       Thread.sleep(10); 
     } 

     monitor.done(); 
    } 
} 

您可以在這裏找到完整的example of usage

+0

我不想設定時間。當新的對話框bx打開時,顯示進度條,我希望它是不確定的,即經歷一個循環,然後我希望控制回到調用程序並執行一些任務,在此任務結束後,我將關閉進度條窗口。 –

+0

沒有必要設定時間。 在開始實際的任務工作之前,只需使用IProgressMonitor.UNKNOWN參數調用beginTask.run。並且您將使用循環動畫​​獲取進度監視器。在monitor.done從後臺任務代碼調用後,該動畫將立即停止。 – Serrega

+0

據我瞭解,前兩行是寫在調用程序中。它在parent.getShell()中顯示錯誤。 –

0

使用try .....

JProgressBar p = new JProgressBar(); 
p.setStringPainted(); 

現在當值需要進行設置。

p.setValue(val); 

要在完成時顯示消息。

p.setString("done"); 
+0

我不想設置一個值。我不知道我的其他任務需要多少時間,所以進度條應該是不確定的。 –

+0

使用setValue()我寫了一個程序,其中我使用了進度條,並根據進度顯示值,如果其花費時間,進度值保持不變直到工作時間未完成...然後相應地進展, ,現在如果你不想使用setValue(),不要使用它..就這麼簡單.. –

+0

對於ProgressBar,未定義setStringPainted()方法。 –