Creating a Moving Progress Bar

Example 16-3 doesn’t show a moving Progress Bar; it simply hardcodes the progress at 50%. It’s easy to create an example that simulates a long-running process, to demonstrate exactly how to create the moving-progress-bar effect.

How do I do that?

In Example 16-3, a button is added to the interface, to simulate the user taking action to initiate some process.

Example 16-3. Simulating a long running process

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.*;
public class ProgressBarExample {
    Display d;
    Shell s;
    ProgressBarExample( )    {
         d = new Display( );
         s = new Shell(d);
        s.setSize(250,250);
        s.setImage(new Image(d, "c:\\icons\\JavaCup.ico"));
        s.setText("A ProgressBar Example");
        final ProgressBar pb = new ProgressBar(s,SWT.HORIZONTAL);
        pb.setMinimum(0);
        pb.setMaximum(100);
        pb.setBounds(10,10,200,20);
        
        Button b = new Button(s, SWT.PUSH);
        b.setBounds(95, 80, 40, 20);
        b.setText("Start");
        b.addSelectionListener(new SelectionAdapter( ) {
            public void widgetSelected(SelectionEvent e) {
                int progress = 0;
                for(int n=0; n<=10000000;n++)
                {
                    if((n%100000)==0)
                    {
                         progress++;
                         pb.setSelection(progress);
                    }                
                }
            }
        });

        s.open( );
        
        while(!s.isDisposed( )){
            if(!d.readAndDispatch( ))
                d.sleep( );
        }
        d.dispose( );
    }
}

In the SelectionListener for the Button is placed a loop that counts from 0 to 80,000,000:

b.addSelectionListener(new SelectionAdapter( ...

Get SWT: A Developer's Notebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.