Question

I am doing a project that need to get page content from web page in Java, and sometimes, I need to execute some javascript on the web page and them get the modified content. So I choose to use SWT tool. Here is part of the code:

public void run(){
    Display.getDefault().asyncExec(new Runnable(){
            public void run(){
                display = Display.getDefault();
                shell = new Shell(display,SWT.CLOSE | SWT.MIN |SWT.TITLE);
                shell.setText("Web Page");
                shell.setSize(1024,768);
                browser = new Browser(shell, SWT.NONE);
                browser.setBounds(0, 0, 1010,700);
                browser.addProgressListener(new ProgressListener() {
                    @Override
                    public void completed(ProgressEvent event) {
                        boolean success = browser.execute(script);
                        if(success || script.length()==0){
                            model.setHtml(browser.getText());
                        }
                        shell.dispose();
                    }

                    @Override
                    public void changed(ProgressEvent event) {

                    }
                });
                browser.setUrl(url);

                while (!shell.isDisposed()) {
                    if (!display.readAndDispatch()) {
                        display.sleep();
                    }
                }
            }
        });
}

And I am calling the the run() function within a class worker which extends from SwingWorker. The worker class is defined like this:

public class worker extends SwingWorker<Object,Integer>{

private ScrapingModel model;
private ScrapingView  view;
private int[] indices;

public worker(ScrapingView v, ScrapingModel m, int[] ins){
    model = m;
    view = v;
    indices = ins; 
}
@Override
protected Object doInBackground() throws Exception {
    int length = indices.length;
    for(int i=0;i<indices.length;i++){
        int index = indices[i];
        //here call the run() function, sorry I skipped some code
        publish((i+1)*100/length);
    }
    return null;
}
@Override
protected void process(List<Integer> chunks) {
    for (Integer chunk : chunks) {
        view.progressBar.setValue(chunk);
    }
}
}

Here is the problem: the code wthin Display.getDefault().asyncExec never executes when I call the run() function in worker class. However, if I tried to call run() outside worker class, it could be executed. Any ideas?

Was it helpful?

Solution

Instead of wrapping the Runnable in an asyncExec

Display.getDefault().asyncExec(new Runnable(){
  // swt code to open shell
 });

Create a new Thread

Runnable r = new Runnable(){
  // swt code to open shell
 }
 Thread t = new Thread(r);
 th.start();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top