实际上,@ Eels的评论并没有停止敲响我的脑袋-并最终注册:这是要走的路,但是不需要任何“人工”结构,因为我们已经 有了 完美的候选人-
这是PropertyChangeEvent本身:-)
从我的问题的总体过程描述中,前三个项目符号保持不变
- 相同:扩展SwingWorker
- 一样:在构造函数中做注册的事情
- 相同:将无限循环放在doInBackground中等待键
- 更改:通过key.pollEvents检索到的每个WatchEvent中创建适当的PropertyChangeEvent并发布PropertyChangeEvent
- 已更改:在过程中触发先前创建的事件(块)
修改后
FileWorker:
@SuppressWarnings("unchecked")public class FileWorker extends SwingWorker<Void, PropertyChangeEvent> { public static final String FILE_DELETeD = StandardWatchEventKinds.ENTRY_DELETE.name(); public static final String FILE_CREATED = StandardWatchEventKinds.ENTRY_CREATE.name(); public static final String FILE_MODIFIED = StandardWatchEventKinds.ENTRY_MODIFY.name(); // final version will keep a map of keys/directories (just as in the tutorial example) private Path directory; private WatchService watcher; public FileWorker(File file) throws IOException { directory = file.toPath(); watcher = FileSystems.getDefault().newWatchService(); directory.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY); } @Override protected Void doInBackground() throws Exception { for (;;) { // wait for key to be signalled WatchKey key; try { key = watcher.take(); } catch (InterruptedException x) { return null; } for (WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind<?> kind = event.kind(); // TBD - provide example of how OVERFLOW event is handled if (kind == OVERFLOW) { continue; } publish(createChangeEvent((WatchEvent<Path>) event, key)); } // reset key return if directory no longer accessible boolean valid = key.reset(); if (!valid) { break; } } return null; } protected PropertyChangeEvent createChangeEvent(WatchEvent<Path> event, WatchKey key) { Path name = event.context(); // real world will lookup the directory from the key/directory map Path child = directory.resolve(name); PropertyChangeEvent e = new PropertyChangeEvent(this, event.kind().name(), null, child.toFile()); return e; } @Override protected void process(List<PropertyChangeEvent> chunks) { super.process(chunks); for (PropertyChangeEvent event : chunks) { getPropertyChangeSupport().firePropertyChange(event); } }}


