Java and SWT: topics and listeners

I am really new to Java and SWT, so my question may sound silly. I looked through intrnet (and stackoverflow), but all the answers and examples are too complicated for a noob like me.

I have a class, name it Admin. When I click the button, it runs the method in another class (Handler).

  • In Admin, I have a progress bar, which should increase with help in the handler.
  • I don’t know how long the operation takes in the Handler, but I know that I have 9 of them.
  • I would like to somehow inform the administrator about the completion of each method.

What I had so far: (inappropriate parts are missing)

Admin.java:

ProgressBar bar = new ProgressBar(this, SWT.SMOOTH); Button btn = new Button(this, SWT.NONE); btn.setText("Update"); btn.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { btn.setEnabled(false); thread.start(); } }); Handler handler = new Handler(); final Thread thread = new Thread(){ public void run() { handler.run(); for(int i=0; i<=10; i++) { final int value = i; try { Thread.sleep(800); } catch (Exception e) { } display.asyncExec(new Runnable(){ public void run() { bar.setSelection(value); } }); } } }; 

Handler.java:

 public class Handler implements Runnable{ void m1() {...} void m2() {...} ... void m9() {...} public void run() { m1(); m2(); ... m9(); } 

With this implementation, the call to handler.run () works fine, and the progress bar fills up, but, of course, they are not "confused" in any way.

I would be grateful for your wisdom! Thank you very much!

+4
source share
2 answers

A high way to resolve this issue is for the Handler accept the ProgressBar as an input in the constructor, and after completing m1() it will update the move to 1/9 and so on. The best (more untied) way to do this is that you can listen to the Handler , and the Handler fires an event with its success after each method completes. Then you can update in Admin.java .

+1
source

I will ask you to consider using JFace's ProgressMonitorDialog if adding this library to your application is not a big problem. Then your code will look something like this:

 ProgressMonitorDialog dialog = new ProgressMonitorDialog(parent); dialog.run(true, true, new IRunnableWithProgress() { @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { monitor.beginTask("my work", 9); m1(); monitor.worked(1); m2(); monitor.worked(1); ... m9(); monitor.done; } }); 

You can also send a monitor instance to your m* methods, even for detailed reporting. Take a look at SubProgressMonitor to divide each of your original 9 ticks further before sending them to each m* method.

But this means that your indicator of progress is a new dialogue that may not be acceptable to you, so in this case the first answer will meet your needs.

+1
source

All Articles