繁体   English   中英

用不同的参数在不同的地方叫秋千工人

[英]Calling swing worker at different places with different parameters

我正在使用swing worker来验证文件,我希望将startLine和endLine发送到validate类,因为我不想每次都验证整个文件。 第一次,当现有文件打开时,我想将startLine发送为0,将endLine发送为endLine = editorTextArea.getLineCount()-1;。 之后,我应该能够每秒发送一次startLine和endLine给我方便。 我该如何实现?

验证类别:

  class Validate implements Runnable {

     private JTextArea editorTextArea;
     private JTextArea errorTextArea;
     private int startLine;
     private int endLine;

     public Validate(JTextArea editor, JTextArea error, startLine, endLine) {
         this.editorTextArea = editor;
         this.errorTextArea  = error;
         this.startLine = startLine;
         this.endLine = endLine;        
    }

@Override
public void run() {
    SwingWorker worker = new SwingWorker<Void, Void>() {
        @Override
        protected Void doInBackground() throws Exception {
            //CODE TO VALIDATE
            return null;
        }

        @Override
        protected void done() {                
            //CODE TO DISPLAY THE RESULT
        }
    };
    worker.execute();
    }
 }

主班:

  //Calls the validate
   public void taskExecutor() {               
          ScheduledExecutorService scheduler =
                 Executors.newSingleThreadScheduledExecutor();
           final ScheduledFuture<?> timeHandle =
                 scheduler.scheduleAtFixedRate(new Validate(editorTextArea,   errorTextArea), 0, 1, SECONDS);                 
}


    private void openFileActionPerformed(java.awt.event.ActionEvent evt)      {                                      

  fileChooser.setCurrentDirectory(new File(".txt"));
int result = fileChooser.showOpenDialog(new JPanel());
int totLines = 0;
String[] content = null;

if (result == JFileChooser.APPROVE_OPTION) {
    try {
        filename = String.valueOf(fileChooser.getSelectedFile());
        setTitle(filename);

        FileReader fr = new FileReader(filename);
        editorTextArea.read(fr, null);
        fr.close();
        startLine = 0;
        endLine = editorTextArea.getLineCount() - 1;
        //here i want to call the validate class once. that is askExecutor();                
    } catch (IOException ex) {
        System.out.println(ex);
    }
}
}

SwingWorker在内部使用ExecutorService ,但是worker“仅设计为执行一次”。 我不明白为什么要在固定速率的Runnable中包装工人。 取而代之的是,一次execute()任务,然后让其publish()临时结果,该结果可以在EDT上进行process() 对于行号, SwingWorker<Boolean, Integer>可能是合适的。 Integer将表示最后处理的行号,而Boolean将表示由doInBackground()返回的最终验证结果。

如果用户正在异步选择多个文件进行验证,请考虑将每个执行工作程序添加到合适的TableModel ,并将结果显示在相应的JTable @mKorbel显示了几个具有JProgressBar 示例

附录:如果您要验证对JTextArea 添加 ,则需要每次execute()一次新工作器,并将新的行号范围作为参数传递给该工作器的构造函数。 示例通过单个int count ,可能表明该方法。 触发器可以是java.util.Timerjavax.swing.Timer甚至是您最初建议的ScheduledExecutorService

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM