如何让方法在后台持续运行?

时间:2014-11-14 11:38:09

标签: java swing pdf background backgroundworker

我希望我的pdf chek方法在后台运行,但我真的不知道如何将我的方法实现到SwingBackgroupWorker或Thread ...

public class PDFCheck extends JPanel {

    private void testAllFontsAreEmbedded(PDFDocument pdf) throws PDFDocumentException {
        for (PDFFont font : pdf.listFonts()) {
            if (!font.isEmbedded()) {
              this.problems.add(new ProblemDescription<PDFDocument>(pdf, "font not embedded: " + font.getName()));
            }
        }
        }
}

非常感谢...

我试过这段代码......但它似乎没有效果......

public static class SwingBackgroupWorker extends SwingWorker<Object, Object> {

        @Override
        protected Object doInBackground() throws Exception {
            private void testAllFontsAreEmbedded(PDFDocument pdf) throws PDFDocumentException {
                for (PDFFont font : pdf.listFonts()) {
                    if (!font.isEmbedded()) {
                      this.problems.add(new ProblemDescription<PDFDocument>(pdf, "font not embedded: " + font.getName()));
                    }
                }
                }
        }

然后我会用new SwingBackgroupWorker().execute();

启动backgroundworker
    }

如何运行Backgroundworker进行测试?

 public class MoveIcon extends JPanel {

        public class MyTask extends SwingWorker<Void, Void> {

            @Override
            protected Void doInBackground() throws Exception {
                int i = 0;

                while (i < 10) {
                    System.out.print(i);
                    i++;
                }
                return null;
            }
        }

    public static void main(String[] args) {

        new MyTask();

    }
}

这不起作用:(

1 个答案:

答案 0 :(得分:1)

我通常会为SwingWorker创建内部类。因此,您可以将SwingWorker放在PDFCheck的私有内部类中,并添加您需要在工作者中访问的字段(在您的情况下只是pdf)。然后,您可以通过构造函数设置它们。你可以这样做:

public class PDFCheck extends JPanel {

/* ... */

    private class MyTask extends SwingWorker<Void, Void> {

        PDFDocument pdf;

        MyTask(PDFDocument pdf)
        {
            this.pdf = pdf;
        }

        @Override
        protected Void doInBackground() throws Exception
        {
            for (PDFFont font : pdf.listFonts()) 
            {
                if (!font.isEmbedded()) 
                {
                    PDFCheck.this.problems.add(new ProblemDescription<PDFDocument>(pdf, "font not embedded: " + font.getName()));
                }
            }
        }
    }

/* ... */

    // Call the Swing Worker from outside the class through this method
    public void runWorker()
    {
         MyTask task = new MyTask(pdfFile);
         task.execute()
    }

}

然后从PDFCheck类中调用它,如下所示:

MyTask task = new MyTask(pdf);
task.execute();