2016-05-04 1 views
0

ボタンコントロールをタイムリーに追加したいと思います。 つまり、シェルを開いた後に、ボタンを1つずつ配置し始めます( )。私はプログラムを書いたが、うまくいかない。すべてのコントロールが配置された後にのみ、すべてのボタン が表示されます。私が推測する若干のリフレッシュの問題。 以下は私のコードです。 UIスレッドで実行さtimerExecに与えられたコントロールの表示が遅れる

public class DelayAddingComponentsExample { 

    public static void main(String[] args) { 
     Display display = new Display(); 
     final Shell shell = new Shell(display); 
     shell.setSize(200, 200); 
     shell.setLayout(new FillLayout(SWT.VERTICAL)); 
     addAutomatically(shell); 
     // removeAutomatically(shell); 
     shell.open(); 
     while (!shell.isDisposed()) { 
      if (!display.readAndDispatch()) { 
       display.sleep(); 
      } 
     } 
     display.dispose(); 
    } 

    public static void addAutomatically(final Shell shell) { 
     for (int i = 0; i < 5; i++) { 
      final Button button = new Button(shell, SWT.NONE); 
      button.setText("Button" + i); 
      button.setVisible(false); 

     } 

     shell.getDisplay().timerExec(0, new Runnable() { 

      @Override 
      public void run() { 

       for (int i = 0; i < 5; i++) { 
        try { 
         Thread.sleep(500); 
         final Button button = new Button(shell, SWT.NONE); 
         button.setText("Button" + i); 
         button.setVisible(true); 
         shell.pack(); 
         shell.layout(true); 
         shell.redraw(); 

        } catch (InterruptedException e) { 
         e.printStackTrace(); 
        } 
       } 

      } 

     }); 
    } 
    public static void removeAutomatically(final Shell shell) { 
     for (int i = 0; i < 5; i++) { 
      final Button button = new Button(shell, SWT.NONE); 
      button.setText("Button" + i); 
      shell.layout(true); 
     } 
     shell.getDisplay().timerExec(0, new Runnable() { 
      @Override 
      public void run() { 
       Control[] controls = shell.getChildren(); 
       for (Control control : controls) { 
        try { 
         Thread.sleep(500); 
         control.dispose(); 
        } catch (InterruptedException e) { 
         e.printStackTrace(); 
        } 
       } 
      } 
     }); 
    } 
} 

答えて

0

Runnable。したがって、Thread.sleepの呼び出しはUIスレッドをブロックしています。このスレッドを決してブロックしないことが不可欠です。 しない UIスレッドでThread.sleepを呼び出します。

別のtimeExecコールを使用して各ステップを実行し、timerExecコールの遅延パラメータを使用して待機時間を指定する必要があります。

ので

shell.getDisplay().timerExec(500, new Runnable() { 
    @Override 
    public void run() 
    { 
    // TODO code for the first button only 

    // Schedule next update 
    shell.getDisplay().timerExec(500, .... code for second button); 
    } 
    }); 

は500ミリ秒内の後のRunnableを実行し、Runnableをちょうど最初のステップを行い、その後、次のステップをスケジュールするために、再度timerExecを呼び出す必要があります。

関連する問題