我正在使用swing worker来验证文件, 我希望将startLine和endLine发送到validate类,因为我不想每次都验证整个文件。第一次当现有文件是openend时,我想将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);
}
}
}
答案 0 :(得分:5)
SwingWorker
内部使用ExecutorService
,但工作人员“只能执行一次。”我不明白为什么你要把工人包裹在按固定费率安排的Runnable
。相反,execute()
任务一次,并让它publish()
在EDT上process()
的中间结果。对于行号,SwingWorker<Boolean, Integer>
可能是合适的。 Integer
代表处理的最后一个代码,而Boolean
代表doInBackground()
返回的最终验证结果。
如果用户异步选择多个文件进行验证,请考虑将每个正在执行的工作人员添加到合适的TableModel
并在相应的JTable
中显示结果。 @mKorbel展示了几个以JProgressBar
为特色的examples。
附录:如果您正在向JTextArea
验证添加,则每次都需要execute()
新工作人员,并将新的行号范围作为worker的构造函数的参数。通过单个int count
的此example可能会提示该方法。触发器可以是java.util.Timer
,javax.swing.Timer
甚至是您最初提出的ScheduledExecutorService
。