我需要在更新swing组件中的值时更改文件后触发事件。这些值存储在文件中。现在我需要检索更新的值。
答案 0 :(得分:0)
查看适用于Java的官方io通知API指南:http://docs.oracle.com/javase/tutorial/essential/io/notification.html
类似的东西:
public class myFileWatcherBean implements ActionListener {
private Component someComponent;
public myFileWatcherBean() {
someComponent.addActionListener(this);
}
public void watchForChanges() {
WatchService watcher = FileSystems.getDefault().newWatchService();
Path dir = ...;
try {
WatchKey key = dir.register(watcher,
ENTRY_CREATE,
ENTRY_DELETE,
ENTRY_MODIFY);
key = watcher.take();
for (WatchEvent<?> event: key.pollEvents()) {
actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, null) {
//Nothing need go here, the actionPerformed method (with the
//above arguments) will trigger the respective listener
});
}
} catch (IOException x) {
System.err.println(x);
}
}
}
PS:代码需要一些修改,但我认为你会得到这个想法。
参考文献: Can I watch for single file change with WatchService (not the whole directory)? How do I manually invoke an Action in swing? http://docs.oracle.com/javase/tutorial/essential/io/notification.html#try http://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html